在 javascript 类 constructor()
中获取数据是一个好习惯吗?
例如在React类constructor()
中,我找到的每个教程都在componendDidMount()
中获取数据,但没有人解释为什么我们不能在constructor( )
。
问题完全涉及 javascript 类,而不仅仅是 react
。
最佳答案
在安装组件之前调用构造函数(如 #constructor 文档:https://reactjs.org/docs/react-component.html 中所述)。
回答你的问题,解释在于react组件的生命周期以及状态改变时需要重绘。通过在构造函数中执行异步调用,您可以在组件安装之前触发 setState。
在构造函数中执行异步调用会扰乱重新渲染,并且如果您在构造函数中调用 setState,您的组件有时不会重新渲染。
来自文档:
You should not call setState() in the constructor(). Instead, if your component needs to use local state, assign the initial state to this.state directly in the constructor:
Avoid introducing any side-effects or subscriptions in the constructor. For those use cases, use componentDidMount() instead.
关于javascript - 在构造函数中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55182526/