在ReactJS中通过AJAX加载初始数据的位置(Where to place logic for loading initial server data in React app?)

编程入门 行业动态 更新时间:2024-10-27 16:37:03
在ReactJS中通过AJAX加载初始数据的位置(Where to place logic for loading initial server data in React app?)

我正在使用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.

更多推荐

本文发布于:2023-08-07 15:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464780.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:加载   位置   数据   place   AJAX

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!