nextState在shouldComponentUpdate中做了什么?

时间:2018-02-05 00:48:06

标签: reactjs react-lifecycle

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

但是nextState做了什么?

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

2 个答案:

答案 0 :(得分:2)

nextState用于检测组件是否应根据您提到的状态更新。

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

如果state变为具有多个属性的大对象,但特定组件仅关注单个属性或状态的一小部分,则可以检查该更改以确定组件是否需要重新呈现。这个例子来自React文档,但是很好地解决了这个问题:

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

答案 1 :(得分:2)

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

相关问题