如何通过点击按钮显示计数器从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作为排序的计时器。
答案 0 :(得分:2)
这样的东西?
当您运行meta
函数时,您将开始每隔一秒将startCounter()
值递增1的间隔。一旦达到counter
(本例中为5),它就会重置。
n
&#13;
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"));
&#13;