reactjs : ShouldComponentUpdate for states

后端 未结 1 513
不知归路
不知归路 2021-01-31 17:05

How can I use shouldComponentUpdate for states?

I can check:

shouldComponentUpdate(nextProps, nextState) {
  return this.state.value != nex         


        
相关标签:
1条回答
  • 2021-01-31 17:29

    The shouldComponentUpdate(nextProps, nextState) method works for both props and state. In your example, after the onClick event the following method is fired by React.

    shouldComponentUpdate(nextProps, nextState) {
      return this.state.value != nextState.value;
    }
    

    The key here is that in the above method the value of this.state.value is equal to what it was before the setState() call. This is thanks to the fact that in React:

    setState() does not immediately mutate this.state but creates a pending state transition.
    React docs: https://facebook.github.io/react/docs/component-api.html#setstate

    Have a look at this demo: http://codepen.io/PiotrBerebecki/pen/YGZgom (full code below)

    React keeps on state the count of every click on the button and also saves the randomly picked value (true or false). However thanks to the shouldComponentUpdate method, the component is re-rendered only if the previous value is not equal to upcoming / new value. This is why the displayed click count sometimes skips rendering its current state. You can comment out the whole shouldComponentUpdate method to re-render on every click.

    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')
    );
    
    0 讨论(0)
提交回复
热议问题