关于react.js:react源码解析11生命周期调用顺序

2次阅读

共计 904 个字符,预计需要花费 3 分钟才能阅读完成。

各阶段生命周期执行状况

函数组件 hooks 的周期会在 hooks 章节解说,这一章的使命周期次要针对类组件,各阶段生命周期执行状况看下图:

  • render 阶段:

    1. mount 时:组件首先会经验 constructor、getDerivedStateFromProps、componnetWillMount、render
    2. update 时:组件首先会经验 componentWillReceiveProps、getDerivedStateFromProps、shouldComponentUpdate、render
    3. error 时:会调用 getDerivedStateFromError
  • commit 阶段

    1. mount 时:组件会经验 componnetDidMount
    2. update 时:组件会调用 getSnapshotBeforeUpdate、componnetDidUpdate
    3. unMount 时:调用 componnetWillUnmount
    4. error 时:调用 componnetDidCatch

其中红色的局部不倡议应用,须要留神的是 commit 阶段生命周期在 mutation 各个子阶段的执行程序,能够温习上一章

接下来依据一个例子来解说在 mount 时和 update 时更新的具体程序:

相干参考视频解说:进入学习

  • mount 时:首先会依照深度优先的形式,顺次构建 wip Fiber 节点而后切换成 current Fiber,在 render 阶段会顺次执行各个节点的 constructor、getDerivedStateFromProps/componnetWillMount、render,在 commit 阶段,也就是深度优先遍历向上冒泡的时候顺次执行节点的 componnetDidMount
  • update 时:同样会深度优先构建 wip Fiber 树,在构建的过程中会 diff 子节点,在 render 阶段,如果返现有节点的变动,例如上图的 c2,那就标记这个节点 Update Flag,而后执行 getDerivedStateFromProps 和 render,在 commit 阶段会顺次执行节点的 getSnapshotBeforeUpdate、componnetDidUpdate
正文完
 0