且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在哪里放置用于在 React 应用程序中加载初始服务器数据的逻辑?

更新时间:2023-10-12 09:23:40

编辑:Dan Abramov 最近表示

在 React 的未来版本中,我们预计 componentWillMount 在某些情况下会触发不止一次,所以你应该使用 componentDidMount 来处理网络请求.

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.


componentDidMount

阅读此处.

在 componentDidMount 中获取数据.当响应到达时,将数据存储在 state 中,触发渲染以更新您的 UI.

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

异步获取数据时,在卸载组件之前使用 componentWillUnmount 取消任何未完成的请求.

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

关于为什么在 componentDidMount 中"的文档非常少.我相信如果您使用服务器端渲染,则不会调用 componentWillMount,因此这可能是首选 componentDidMount 的原因.

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.