我正在使用React-Redux来构建应用程序。 要加载React智能组件的初始数据,我需要调度一个Redux操作,在该操作中将发生Ajax调用。 我已经尝试在构造函数(ES6实现),componentWillMount和componentsnetDidMount中调度操作。 他们都工作了。 我的问题是:在React智能组件中是否有推荐的位置应该调度该操作。
I am using React-Redux to build an application.
To load initial data for a React smart component, I need to dispatch a Redux action where the server data requests will happen.
I've tried dispatching the action in constructor (ES6 implementation), componentWillMount, and componenetDidMount. They all worked.
My question is:
is there a recommended place in the React smart component that the action should be dispatched.
最满意答案
编辑 : 丹阿布拉莫夫最近说
在React的未来版本中,我们希望componentWillMount在某些情况下会多次触发,因此您应该将componentDidMount用于网络请求。
在componentDidMount
在这里阅读
获取componentDidMount中的数据 。 响应到达时,将数据存储在状态中,触发渲染以更新UI。
在异步获取数据时, 使用componentWillUnmount在卸载组件之前取消所有未完成的请求 。
关于“为什么在componentDidMount ”的文档非常缺乏。 我相信如果您使用服务器端渲染,则不会调用componentWillMount ,因此这可能是首选componentDidMount的原因。
Edit: Dan Abramov recently stated
In future versions of React we expect that componentWillMount will fire more than once in some cases, so you should use componentDidMount for network requests.
In componentDidMount
Read here.
Fetch data in componentDidMount. When the response arrives, store the data in state, triggering a render to update your UI.
When fetching data asynchronously, use componentWillUnmount to cancel any outstanding requests before the component is unmounted.
Documentation is really scarce on "why in componentDidMount". I believe componentWillMount is not called if you use server-side render, so this could be a reason why componentDidMount is preferred.
更多推荐
发布评论