从构造函数调用操作与生命周期方法 [英] Calling action from constructor vs a life cycle method
问题描述
哪里是调用操作的最佳位置,该操作将进行 API 调用以补充我的状态?构造函数或生命周期方法之一,例如ComponentWillMount?
Where's the best place to call an action that will make an API call to hydrate my state? Constructor or one of the life cycle methods e.g. ComponentWillMount?
推荐答案
从生命周期方法 componentDidMount
调用 api 会更好,react doc 也建议相同.
It will be better to make the api calls from lifecycle method componentDidMount
, react doc also suggested the same.
根据DOC:
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.
这篇关于从构造函数调用操作与生命周期方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!