getDerivedStateFromProps

919 阅读1分钟

为了配合接下来 React 异步渲染的机制,getDerivedStateFromProps 终究与我们之前理解的componentWillReceiveProps 不一样了,这篇博文 React v16.4.0: Pointer Events – React Blog 给予了详细的解释,对于以前我们利用到 componentWillReceiveProps 来处理前后 Props 变化时的场景,在新的静态方法中,稍有不同。

getDerivedStateFromProps 不仅 render 时会被调用,setState 时也会被触发,因此我们可能需要:

class App extends React.Component<IProps, IState> {
  public static getDerivedStateFromProps(nextProps: Readonly<IProps>, preState: IState){
    // ... nextProps ... preState.preProps 这样的比对
    // preState.preProps = nextProps   最后将下一个 Props 赋值给 State 的 preProps
  }
  constructor(props: IProps){
    super(props);
    this.state = {
      preProps: props
    }
  }
}

把前一个的 Props 在初始化时赋值给 State,在 getDerivedStateFromProps 处理完成结果之后,还需要再次将新的 Props 赋值给 State.preProps 属性。这里的返回,即是一个新的 State。

还有一个场景是针对更新的,比如当启动变化时,我们可能会去请求一次网络,但是某些情况下,这是一个较为细微的处理方式:

public componentDidUpdate() {

}

在 componentDidUpdate 生命周期中(这是一个实例方法)去处理网络活动以及其他的更新。