React生命周期
初始化
constructor: 在构造函数中可以初始化state
渲染
render:渲染组件
挂载前后
componentWillMount:在渲染前调用
componentDidMount:第一次渲染后调用
更新
componentWillReceiveProps:在接收到新的props时调用,render阶段不会被调用
shouldComponentUpdate:接受到新的props、state时调用,返回布尔值确定是否更新组件
componentWillUpdate:在接收到新的props或state但未render时被调用
componentDidUpdate:组件更新完成后调用
移除
componentWillUnmount:组件被移除时调用
生命周期执行顺序
生命周期执行顺序如下图所示:
请求数据最佳时机
componentWillMount和componentDidMount
在实习过程中我刚开始写组件时,把请求数据放在了componentWillMount中,在观察了前辈们写的组件时,发现他们请求数据的代码没有放在componentWillMount中,而是写在componentDidMount中,下来查了资料后,发现在下个版本中:
- React将移除componentWillMount这个生命周期
- componentWillMount在16.3版本前是同步的,在这里执行请求可能不会触发UI渲染,16.3版本后,这个生命周期是异步的,在这里请求可能会导致多次调用这个生命周期并且造成内存泄漏
- componentDidMount不论异步还是同步都只会调用一次
所以综合考虑后,请求数据的最佳时机在componentDidMount