【问题标题】:Why isn't setState() in react updating state during recurrent calls?为什么 setState() 在循环调用期间不响应更新状态?
【发布时间】:2020-10-04 09:09:00
【问题描述】:

我已经开始学习 react 使用官方文档遇到了这个“React 可能将多个 setState() 调用批处理到单个更新中以提高性能。因为 this.props 和 this.state 可能会异步更新,所以你不应该依赖它们用于计算下一个状态的值。”在实践中,我遇到了这个问题,我认为这在某种程度上与此有关,但我仍然不明白为什么 sn-p(1) 不起作用而 sn-p(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】:

    我认为如果你只是在你的第一个 sn-p 的增量方法中添加“this”,它会完美地工作:

     increment() {
        var newCount = this.state.count + 1; //you forgot the this keyword on this line
        this.setState({count: newCount});
      }
    

    【讨论】:

    • 您是对的,但您没有回答为什么代码 sn-p 2 有效而代码 sn-p 1 无效。这是因为代码 sn-p 2 使用 setState 的回调语法,它将当前状态作为参数传递给回调。在代码 sn -p 1 中没有这样的参数,因为询问者想要在调用 setState 之前访问状态,所以必须通过 this.state 来访问。
    【解决方案2】:

    因为 setState 以异步方式工作。这意味着在调用 setState 后 this.state 变量不会立即更改。因此,如果您想在设置状态后立即执行操作,则状态可能具有较旧的值,因此第二次状态更新可能不考虑先前的状态值。

    在第二个脚本中,回调函数将始终使用最后一个状态值,这就是为什么第二种方法可以正常工作的原因。

    而且您在第一个片段中缺少 this 关键字中的 this 关键字。

    【讨论】:

      猜你喜欢
      • 2019-01-05
      • 1970-01-01
      • 2018-12-08
      • 2019-07-26
      • 2016-05-16
      • 2020-03-13
      • 1970-01-01
      • 2019-09-28
      相关资源
      最近更新 更多