在 shouldComponentUpdate 中 nextState 做了什么?

Fel*_*ger 5 reactjs react-lifecycle

在 React 生命周期函数shouldComponentUpdate(nextProps, nextState) 中, nextProps 是不言自明的。

但是 nextState 做什么呢?

在决定是否应该渲染/修改组件之前,我可以评估即将到来的状态,这听起来不太对。

Liv*_*ing 6

基本上状态在那一点已经改变了,你是否认为有必要重新渲染组件并基于此返回 true 或 false


Dan*_*n D 5

nextState 用于检测组件是否应该像您提到的那样根据即将到来的状态进行更新。

这有助于优化更新组件。例如:

如果状态变成了具有多个属性的大对象,但特定组件只关心单个属性或状态的一小部分,您可以检查该更改以确定组件是否需要重新渲染。这个例子取自 React 文档,但很好地说明了这一点:

shouldComponentUpdate(nextProps, nextState) {
    if (this.props.color !== nextProps.color) {
      return true;
    }
    if (this.state.count !== nextState.count) {
      return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)