componentWillReceiveProps 与 static getDerivedStateFromProps() 区别

579 阅读1分钟

两者的主要作用都是用于根据 props 的变更来更新组件内部的 state

两者接收的参数不一样:

  • componentWillReceiveProps 只接收一个参数 props

  • static getDerivedStateFromProps() 接收两个参数 props 和 state

两者的执行时机不相同:

  • getDerivedStateFromProps 会在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用。它应返回一个对象来更新 state,如果返回 null 则不更新任何内容。

  • componentWillReceiveProps 在初始挂载时不会调用,即首次进入页面的时候 componentWillReceiveProps 不会执行,组件内部调用 this.setState 也不会调用,只会在组件的 props 更新时调用或者是由于父组件导致组件重新渲染,此时即使 props 没有更改,也会调用。

  • 如果在组件里面同时使用 static getDerivedStateFromProps()componentWillReceiveProps ,则只会执行 static getDerivedStateFromProps() ,不会执行 componentWillReceiveProps

相关代码例子:life-cycle-demo