如何通过单击按钮显示计数器从 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 作为排序计时器。
最佳答案
是这样的吗?
当您运行 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>
关于javascript - 在循环中更改 setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44064357/