敲重点
- 在初始化和更新阶段,执行父组件生命周期函数先执行到
render,再执行完子组件整个阶段的生命周期函数,再执行父组件render之后的生命周期函数。 - 在销毁阶段,先执行子组件的生命周期函数,再执行父组件的生命周期函数。
1. 初始化阶段(Mounting Phase)
当组件第一次被挂载到 DOM 中时,生命周期函数的执行顺序如下:
-
父组件
constructor()static getDerivedStateFromProps()render()
-
子组件
constructor()static getDerivedStateFromProps()render()componentDidMount()(子组件)
-
父组件
componentDidMount()(父组件)
2. 更新阶段(Updating Phase)
当组件的 props 或 state 发生变化时,生命周期函数的执行顺序如下:
-
父组件
static getDerivedStateFromProps()shouldComponentUpdate()render()
-
子组件
static getDerivedStateFromProps()shouldComponentUpdate()render()getSnapshotBeforeUpdate()componentDidUpdate()(子组件)
-
父组件
getSnapshotBeforeUpdate()componentDidUpdate()(父组件)
3. 卸载阶段(Unmounting Phase)
当组件从 DOM 中移除时,生命周期函数的执行顺序如下:
-
子组件
componentWillUnmount()(子组件)
-
父组件
componentWillUnmount()(父组件)
注意: 如果父组件的更新导致子组件被卸载,那么子组件的 componentWillUnmount() 会在父组件的 componentDidUpdate() 之前执行。