为什么setState()在循环调用期间不处于更新状态?

问题描述 投票:0回答:1

我已经开始学习使用此文档遇到的官方文档做出反应,“ React可能将多个setState()调用批处理为单个更新以提高性能。由于this.props和this.state可能异步更新,因此您不应依赖它们用于计算下一个状态的值。”在练习时,我遇到了这个问题,我认为这在某种程度上与这个问题有关,但是我仍然不明白为什么snippet(1)不起作用而snippet(2)起作用。

   //  code-snippet(1)

    import React from "react";
    import ReactDOM from 'react-dom';
    import "./styles.css";
    class Count extends React.Component {
      constructor(props) {
        super(props);
        this.state = {count : 0};
      }
      increment() {
        var newCount = state.count + 1;
        this.setState({count: newCount});
      }
      increment5() {
        this.increment();
        this.increment();
        this.increment();
        this.increment();
        this.increment();
      }
      render() {
        return (
        <div>
          <h1>Count - {this.state.count}</h1>
          <button onClick={() => this.increment5()}>Increment</button>
        </div>
        );
      }
    }
     ReactDOM.render(<Count />, document.getElementById("root"));


//   code-snippet(2)

     import React from "react";
        import ReactDOM from 'react-dom';
        import "./styles.css";
        class Count extends React.Component {
          constructor(props) {
            super(props);
            this.state = {count : 0};
          }
          increment() {
            this.setState(function(state) {
              var newCount = state.count + 1;
              return {count : newCount};
            });
          }
          increment5() {
            this.increment();
            this.increment();
            this.increment();
            this.increment();
            this.increment();
          }
          render() {
            return (
            <div>
              <h1>Count - {this.state.count}</h1>
              <button onClick={() => this.increment5()}>Increment</button>
            </div>
            );
          }
        }
         ReactDOM.render(<Count />, document.getElementById("root"));
javascript reactjs rxjs state setstate
1个回答
1
投票

我认为,如果您仅在第一个代码段的增量方法中添加“ this”,则效果会很好:

 increment() {
    var newCount = this.state.count + 1; //you forgot the this keyword on this line
    this.setState({count: newCount});
  }
© www.soinside.com 2019 - 2024. All rights reserved.