【问题标题】:Changing setState in loop在循环中更改 setState
【发布时间】:2017-05-19 07:47:03
【问题描述】:

如何在单击按钮时显示从 1 到 2 到 3 到 n 的计数器。我试过在 for 循环中做一个 setState ,但那没有用。 我知道 react 的 setState 是异步的,我什至尝试过使用 prevState,但它不起作用。

import React, { Component } from 'react';

class App extends Component {

    constructor(props) {
        super(props);
      this.state = {
      counter: 0

      };

      this.startCounter = this.startCounter.bind(this);
    }

    startCounter() {
      const self = this;
      for (let i = 0; i < 100; i++) {
        this.setState(prevState => {
          const counter = prevState.counter + 1;
          return Object.assign({}, prevState, {counter: counter})
        });
      }
    }

    render() {
        return (
            <div>
              Counter Value: {this.state.counter}
               <button onClick={this.startCounter}>Start Counter</button>
            </div>
        )
    }
}

export default App;

webpack bin 下面

https://www.webpackbin.com/bins/-KkU1NJA-ectflyDgf_S

我想在点击时将计数从 0 增加到 n 作为各种计时器。

【问题讨论】:

    标签: javascript reactjs setstate


    【解决方案1】:

    这样的?

    当您运行startCounter() 函数时,您将启动间隔,该间隔每秒将counter 的值增加1。一旦达到n(本例中为5),它就会重置。

    class App extends React.Component {
      constructor() {
        super();
        this.interval;
        this.state = {
          counter: 1,
          n: 5
        };
      }
    
      startCounter = () => {
        if (this.interval) return; //if the timer is already running, do nothing.
        this.interval = setInterval(() => {
          let c = (this.state.counter % this.state.n) + 1;
          this.setState({
            counter: c
          });
        }, 1000);
      }
    
      componentWillUnmount() {
        clearInterval(this.interval); //remove the interval if the component is unmounted.
      }
    
      render() {
        return ( 
          <div>
            Counter Value: {this.state.counter}
            <button onClick={this.startCounter}>Start Counter</button>
          </div>
        );
      }
    }
    ReactDOM.render(<App />, document.getElementById("app"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="app"></div>

    【讨论】:

    • 如果没有 setInterval 只使用 for 循环,这将无法完成。
    • @NitishPhanse,您希望它在每次点击时自动向上计数还是 +1?
    • 不,那将是直截了当的..当我单击计时器时,我希望它从 0 增加到 N(这里为 100)。先 1 后 2 ..100
    • 就像我在上面所做的那样,对吧?不,您必须使用interval 执行此操作。在 for 循环中设置状态在很多方面都是不好的做法。最大的问题是计算机会在你说杰克罗宾逊之前完成这个循环。 :) 这个 ^ 就是你的做法。
    • @NitishPhanse,当计数器到达n 时会发生什么?
    猜你喜欢
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多