问题描述
在javascript类 constructor()
中获取数据是一种好习惯吗?
Is a good practice to fetch data in javascript class constructor()
?
例如在react类 constructor()
中,我找到的每个教程都在 componendDidMount()
中获取数据,但是没有人解释为什么我们不能在 constructor()
.
E.g. In react class constructor()
, every tutorial which I find fetch data in componendDidMount()
, but no one explein why We can't do it in constructor()
.
问题完全与javascript类有关,而不仅仅是 react
.
Question concerns javascript classes at all, not only react
.
推荐答案
在安装组件之前调用构造函数(如#constructor doc中的此处所述: https://reactjs.org/docs/react-component.html ).
Constructor is called before the component is mounted (as stated here in #constructor doc: https://reactjs.org/docs/react-component.html).
要回答您的问题,解释在于React组件的生命周期以及在状态更改时需要重画的需求.通过在构造函数中进行异步调用,可以在安装组件之前触发setState.
To answer your question, the explanation lies in the lifecycle of a react component and the need to redraw when the state changes. By doing async calls in constructor, you may trigger setState before your component is mounted.
如果在构造函数中调用setState,则在构造函数中进行异步调用会导致重新渲染,并且有时组件不会重新渲染.
Doing async calls in constructor will mess with the re-render and your component will sometimes not re-render if you call setState in the constructor.
来自文档:
避免在构造函数中引入任何副作用或订阅.对于这些用例,请改用componentDidMount().
Avoid introducing any side-effects or subscriptions in the constructor. For those use cases, use componentDidMount() instead.
这篇关于在构造函数中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!