React新生命周期--getDerivedStateFromProps

1,069 阅读1分钟

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

使用:

static getDerivedStateFromProps(nextProps, prevState) {
    const {type} = nextProps;
    // 当传入的type发生变化的时候,更新state
    if (type !== prevState.type) {
        return {
            type,
        };
    }
    // 否则,对于state不进行任何操作
    return null;
} 

可能使用的两个场景:

  • 无条件的根据prop来更新内部state,也就是只要传入prop值,就更新state
  • 只有prop值和state值不同时才更新state值