在React.js中我应该在componentWillMount或componentDidMount中创建我的初始网络请求吗? [英] In React.js should I make my initial network request in componentWillMount or componentDidMount?

查看:278
本文介绍了在React.js中我应该在componentWillMount或componentDidMount中创建我的初始网络请求吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在react文档中,它建议在 componentDidMount 方法中发出初始网络请求:

In the react docs it recommends making initial network requests in the componentDidMount method:


装载组件后立即调用

componentDidMount()。需要DOM节点的初始化应该放在这里。如果您需要从远程端点加载数据,这是实例化网络请求的好地方。在此方法中设置状态将触发重新渲染。

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.

如果在渲染组件之前调用 componentWillMount ,请不要在此处发出请求并设置状态?如果我在 componentDidMount 中执行此操作,则会呈现组件,发出请求,更改状态,然后重新呈现组件。为什么在呈现任何内容之前做出请求更好?

If componentWillMount is called before rendering the component, isn't it better to make the request and set the state here? If I do so in componentDidMount, the component is rendered, the request is made, the state is changed, then the component is re-rendered. Why isn't it better to make the request before anything is rendered?

推荐答案

你应该在 componentDidMount 。


如果在渲染组件之前调用componentWillMount,那么发出请求是不是更好并在此处设置状态?

If componentWillMount is called before rendering the component, isn't it better to make the request and set the state here?

否,因为请求无法在组件呈现时完成。

No because the request won’t finish by the time the component is rendered anyway.


如果我在componentDidMount中执行此操作,则会呈现组件,发出请求,更改状态,然后重新组件渲染。为什么在呈现任何内容之前提出请求更好?

If I do so in componentDidMount, the component is rendered, the request is made, the state is changed, then the component is re-rendered. Why isn't it better to make the request before anything is rendered?

因为任何网络请求都是异步。除非你缓存了数据,否则无论如何都无法避免第二次渲染(在这种情况下,您根本不需要触发请求)。 你不能通过先前解雇来避免第二次渲染。它无济于事。

Because any network request is asynchronous. You can't avoid a second render anyway unless you cached the data (and in this case you wouldn't need to fire the request at all). You can’t avoid a second render by firing it earlier. It won’t help.

在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.

这篇关于在React.js中我应该在componentWillMount或componentDidMount中创建我的初始网络请求吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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