为什么即使状态保持不变,setState也会重新渲染?

时间:2018-03-15 02:13:26

标签: reactjs

class App extends React.Component {
  state = {
    index: 0,
  }
  render() {
    alert('rendered');
    return(
      <div>
        <h1>{this.state.index}</h1>
        <button onClick={() => this.setState({index: 0})}>test</button>
      </div>
    );
  } 
}

Edit zw28l3ynkm

我知道我们可以定义一个shouldComponentUpdate来检查this.state === nextState,但为什么不反应检查这个默认情况?道具也一样。

1 个答案:

答案 0 :(得分:0)

React默认为始终重新呈现,因为无论您在state中拥有什么,默认情况下React始终都是正确的。

迭代this.state的密钥并使用===在您的示例中有效,但对于复杂的state,无法使用简单的相等性。以下面的示例为例,indices数组是相同的数组,因此===将返回true

class App extends React.Component {
  state = {
    indices: [0],
  }
  render() {
    alert('rendered');
    return(
      <div>
        <h1>{this.state.index}</h1>
        <button onClick={() => {
          this.state.indices.push(2);
          this.setState({indices: this.state.indices})
        }>test</button>
      </div>
    );
  } 
}

状态可以有数组,对象等,而React并不试图推断“等式”对他们意味着什么。如果要优化组件,可以实现shouldComponentUpdate,因为您知道“等式”对您自己的状态意味着什么。

如果你确定你的组件的状态&amp;可以使用简单的相等性来比较道具,就像在您的示例中一样,您可以扩展React.PureComponent以获得您描述的行为。

相关问题