Skip to content

React生命周期

React 一次状态更新,一共分为 2 个阶段、4 个生命周期。

2 个阶段:

  1. render阶段:包含Diff算法,计算出状态变化
  2. commit渲染阶段:ReactDom渲染器,将状态变化渲染在视图中

4个生命周期:

  1. Mout(第一次挂载)
  2. Update(更新)
  3. Unmout(卸载)
  4. Error(子项发生错误)
生命周期函数所属阶段所属生命周期
constructorRender阶段Mount
componentWillReceivePropsRender阶段Update
getDerivedStateFromPropsRender阶段并存于Moun、Update
getDerivedStateFromErrorRender阶段Error
shouldComponentUpdateRender阶段Update
componentWillMountRender阶段Mount
componentWillUpdateRender阶段Update
renderRender阶段并存于Mount、Update
componentDidMountCommit阶段Mount
getSnapshotBeforeUpdateCommit阶段Update
componentDidUpdateCommit阶段Update
componentWillUnmountCommit阶段Unmount
componentDidCatchCommit阶段Error

注意事情:

componentWillReceivePropscomponentWillMountcomponentWillUpdate 这 3 个生命周期函数正在逐步被 React 官方放弃使用,不推荐继续使用这 3 个生命周期函数。

与之对应的是 getDerivedStateFromPropsgetDerivedStateFromError 这 2 个这是被推荐使用的。

关于各个生命周期函数详细介绍,可以参考 React 官方文档

补充说明:

目前并不是所有的生命周期函数都对应有 hook 函数。