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

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

  • 首次加载:parent-constructor => parent-getDerivedStateFromProps => parent-render => child-constructor => child-getDerivedStateFromProps => child-render => child-componentDidMount => parent-componentDidMount

  • 更新组件:parent-getDerivedStateFromProps => parent-shouldComponentUpdate => parent-render => child-getDerivedStateFromProps => child-shouldComponentUpdate => child-render => child-componentDidUpdate => parent-componentDidUpdate

  • 销毁组件:parent-componentWillUnmount => child-componentWillUnmount

生命周期详情:

  • 挂载:constructor()static getDerivedStateFromProps()render()componentDidMount()

  • 更新:static getDerivedStateFromProps()shouldComponentUpdate()render()getSnapshotBeforeUpdate()componentDidUpdate()

  • 错误处理:static getDerivedStateFromError()componentDidCatch()

  • 卸载:componentWillUnmount()

生命周期示意

各个函数用途:

  • constructor():组件构造函数,在组件挂载之前调用;仅用于初始化内部state以及为事件处理函数绑定实例;

  • static getDerivedStateFromProps():会在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用,此方法适用于state 的值在任何时候都取决于 props;

  • render():是 class 组件中唯一必须实现的方法;

  • componentDidMount():会在组件挂载后(插入 DOM 树中)立即调用;

  • shouldComponentUpdate():根据该函数的返回值,来确定组件是否重新渲染;

  • getSnapshotBeforeUpdate():在最近一次渲染输出(提交到 DOM 节点)之前调用;此生命周期方法的任何返回值将作为参数传递给 componentDidUpdate()

  • componentDidUpdate():会在更新后会被立即调用,首次渲染不会执行此方法;

  • componentWillUnmount():会在组件卸载及销毁之前直接调用;

  • static getDerivedStateFromError():此生命周期会在后代组件抛出错误后被调用。 它将抛出的错误作为参数,并返回一个值以更新 state;它会在渲染阶段调用,因此不允许出现副作用

  • componentDidCatch():此生命周期在后代组件抛出错误后被调用,会在“提交”阶段被调用,因此允许执行副作用。