react生命周期

react生命周期

初始化

此阶段会在constructor进行初始化赋值操作。

注意

此时不应该将props的数据在constructor赋值给state,因为当父组件prop的值改变时,子组件不会再次执行constructor。应在生命周期componentWillReceiveProps中重新赋值

挂载阶段

此阶段主要生命周期为componentWillMountcomponentDidMount
流程为 componentWillMount => render => componentDidMount

更新阶段

此阶段由于state和props更新引起

流程为:
componentWillReceiveProps(nextProps, nextState) => shouldComponetUpdate => componentWillUpdate => render => componentDidUpdate

state更新没有componentWillReceiveProps过程

卸载阶段

componentWillUnmount
omponentWillUnmount 中不应调用 setState,因为该组件将永远不会重新渲染。组件实例卸载后,将永远不会再挂载它

注意

在react16中去掉了
componentWillMount,
componentWillReceiveProps,
componentWillUpdate,
这三个生命周期

新增了:
getDerivedStateFromProps(nextProps,nextState)在组件实例化、接收到新的 props 、组件状态更新时会被调用

getSnapshotBeforeUpdate(prevProps,prevState)
在 render 函数调用之后,实际的 Dom 渲染之前,在这个阶段我们可以拿到上一个状态 Dom 元素的坐标、大小的等相关信息。用于替代旧的生命周期中的 componentWillUpdate。
该函数的返回值将会作为 componentDidUpdate 的第三个参数出现。

总结

react生命周期分为初始化-挂载-更新-销毁
初始化会执行constructor
挂载包括componentWillMount,componentDidMount
更新包括componentWillRecieveProps=>shouldComponentUpdate=>componentWillUpdate=>render=>componentDidUpdate
卸载包括componentWillUnmount

https://segmentfault.com/a/1190000022880456