reactjs : ShouldComponentUpdate for states

后端 未结 1 514
不知归路
不知归路 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 (
          
    shouldComponentUpdate demo

    {this.state.value.toString()}

    Count of clicks: {this.state.countOfClicks}

    ); } } ReactDOM.render( , document.getElementById('app') );

    0 讨论(0)
提交回复
热议问题