最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Where to place logic for loading initial server data in React app? - Stack Overflow

programmeradmin0浏览0评论

I am using React-Redux to build an application.

To load initial data for a React smart ponent, I need to dispatch a Redux action where the server data requests will happen.

I've tried dispatching the action in constructor (ES6 implementation), ponentWillMount, and ponenetDidMount. They all worked.


My question is:

is there a remended place in the React smart ponent that the action should be dispatched.

I am using React-Redux to build an application.

To load initial data for a React smart ponent, I need to dispatch a Redux action where the server data requests will happen.

I've tried dispatching the action in constructor (ES6 implementation), ponentWillMount, and ponenetDidMount. They all worked.


My question is:

is there a remended place in the React smart ponent that the action should be dispatched.

Share Improve this question edited Jul 4, 2019 at 8:33 vsync 131k59 gold badges340 silver badges422 bronze badges asked Sep 21, 2016 at 15:19 JaneJane 6511 gold badge7 silver badges10 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

Edit: Dan Abramov recently stated

In future versions of React we expect that ponentWillMount will fire more than once in some cases, so you should use ponentDidMount for network requests.


In ponentDidMount

Read here.

Fetch data in ponentDidMount. When the response arrives, store the data in state, triggering a render to update your UI.

When fetching data asynchronously, use ponentWillUnmount to cancel any outstanding requests before the ponent is unmounted.

Documentation is really scarce on "why in ponentDidMount". I believe ponentWillMount is not called if you use server-side render, so this could be a reason why ponentDidMount is preferred.

The remended way is, I believe, to do it in ponentDidMount. See this for more info.

发布评论

评论列表(0)

  1. 暂无评论