reactjs:ShouldComponentUpdate for states

Nic*_*ick 29 reactjs

我怎样才能shouldComponentUpdate用于州?

我可以查一下:

shouldComponentUpdate(nextProps, nextState) {
  return this.state.value != nextState.value;
}
Run Code Online (Sandbox Code Playgroud)

但它对国家没有任何意义.因为如果我改变state(this.setState({value: 'newValue'}))this.state将是平等的 nextState.

例如,onClick事件:

handleClick() {
  this.setState({value: 'newValue'});
}
Run Code Online (Sandbox Code Playgroud)

Pio*_*cki 23

shouldComponentUpdate(nextProps, nextState)方法适用于道具和州.在您的示例中,onClick事件发生后,React会触发以下方法.

shouldComponentUpdate(nextProps, nextState) {
  return this.state.value != nextState.value;
}
Run Code Online (Sandbox Code Playgroud)

这里的关键是在上面的方法中,值this.state.value等于调用之前的值setState().这要归功于React:

setState()不会立即改变this.state,但会创建挂起状态转换.
反应文档:https://facebook.github.io/react/docs/component-api.html#setstate

看看这个演示:http://codepen.io/PiotrBerebecki/pen/YGZgom(完整代码如下)

React保持状态按钮上的每次点击的计数,并保存随机选择的value(真或假).但是由于该 shouldComponentUpdate方法,仅当前一个 value不等于即将到来/新时才重新呈现该组件value.这就是显示的点击次数有时会跳过渲染其当前状态的原因.您可以注释掉整个shouldComponentUpdate方法,以便在每次点击时重新渲染.

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      value: true,
      countOfClicks: 0
    };
    this.pickRandom = this.pickRandom.bind(this);
  }

  pickRandom() {
    this.setState({
      value: Math.random() > 0.5, // randomly picks true or false
      countOfClicks: this.state.countOfClicks + 1
    });
  }

  // comment out the below to re-render on every click
  shouldComponentUpdate(nextProps, nextState) {
    return this.state.value != nextState.value;
  }

  render() {
    return (
      <div>
        shouldComponentUpdate demo 
        <p><b>{this.state.value.toString()}</b></p>
        <p>Count of clicks: <b>{this.state.countOfClicks}</b></p>
        <button onClick={this.pickRandom}>
          Click to randomly select: true or false
        </button>
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);
Run Code Online (Sandbox Code Playgroud)

  • 是的,我测试了您的示例。有用。但是在我的真实项目中,“ this.state”等于“ nextState”。那很奇怪。继续寻找。也许我做错了。谢谢。 (2认同)