zoukankan      html  css  js  c++  java
  • react里执行shouldComponentUpdate时返回false的后果

      大家都知道生命周期shouldComponentUpdate返回false时,不会进行后续的渲染,那这个时候state是什么情况呢。我们看一下demo

    class Toggle extends React.Component {
      constructor(props) {
        super(props);
        this.state = {number: 1};
    
        // 这边绑定是必要的,这样 `this` 才能在回调函数中使用
        this.handleClick = this.handleClick.bind(this);
      }
    
      handleClick() {
        this.setState(prevState => ({
          number: this.state.number + 1
        }));
      }
      
      shouldComponentUpdate(nextProps, nextState) {
          if(this.state.number == 4) {
              return false
          }
          return true
      }
    
      render() {
        return (
          <button onClick={this.handleClick}>
            {this.state.number}
          </button>
        );
      }
    }
    
    ReactDOM.render(
      <Toggle />,
      document.getElementById('example')
    );

      number是4的时候,我们返回false。运行结果表明,当按钮的数字是4的时候,再点击,数字不变化,接着点击,数字由4变成了6。表明,shouldComponentUpdate返回false不会影响state的改变,只是不接着进行渲染了而已。

      接下来,应该把生命周期里每个阶段里调用setState会有什么后果,深入搞明白,深入React技术栈30页,还有更多的书籍先看一看。

  • 相关阅读:
    Choosing the Type at Runtime
    User-Defined Components Must Be Capitalized
    Computed property names
    Controlled Components
    Handling Event
    State
    props
    Functional and Class Components
    招聘漂亮的员工
    Spread Syntax
  • 原文地址:https://www.cnblogs.com/zhansu/p/10294496.html
Copyright © 2011-2022 走看看