在哪里放置用于在 React 应用程序中加载初始服务器数据的逻辑? [英] Where to place logic for loading initial server data in React app?

查看:36
本文介绍了在哪里放置用于在 React 应用程序中加载初始服务器数据的逻辑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 React-Redux 来构建应用程序.

I am using React-Redux to build an application.

要为 React 智能组件加载初始数据,我需要分派一个 Redux 操作,其中将发生服务器数据请求.

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

我尝试在构造函数(ES6 实现)、componentWillMountcomponenetDidMount 中分派动作.他们都工作了.

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

React 智能组件中是否有推荐的应该调度操作的位置.

is there a recommended place in the React smart component that the action should be dispatched.

推荐答案

编辑: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.

这篇关于在哪里放置用于在 React 应用程序中加载初始服务器数据的逻辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆