react 子父组件生命周期执行顺序

276 阅读1分钟

敲重点

  1. 在初始化和更新阶段,执行父组件生命周期函数先执行到 render,再执行完子组件整个阶段的生命周期函数,再执行父组件 render 之后的生命周期函数。
  2. 在销毁阶段,先执行子组件的生命周期函数,再执行父组件的生命周期函数。

1. 初始化阶段(Mounting Phase)

当组件第一次被挂载到 DOM 中时,生命周期函数的执行顺序如下:

  1. 父组件

    • constructor()
    • static getDerivedStateFromProps()
    • render()
  2. 子组件

    • constructor()
    • static getDerivedStateFromProps()
    • render()
    • componentDidMount()(子组件)
  3. 父组件

    • componentDidMount()(父组件)

2. 更新阶段(Updating Phase)

当组件的 props 或 state 发生变化时,生命周期函数的执行顺序如下:

  1. 父组件

    • static getDerivedStateFromProps()
    • shouldComponentUpdate()
    • render()
  2. 子组件

    • static getDerivedStateFromProps()
    • shouldComponentUpdate()
    • render()
    • getSnapshotBeforeUpdate()
    • componentDidUpdate()(子组件)
  3. 父组件

    • getSnapshotBeforeUpdate()
    • componentDidUpdate()(父组件)

3. 卸载阶段(Unmounting Phase)

当组件从 DOM 中移除时,生命周期函数的执行顺序如下:

  1. 子组件

    • componentWillUnmount()(子组件)
  2. 父组件

    • componentWillUnmount()(父组件)

注意: 如果父组件的更新导致子组件被卸载,那么子组件的 componentWillUnmount() 会在父组件的 componentDidUpdate() 之前执行。