import { Component } from "react";
export class SimpleButton extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0,
}
}
render() {
return (
<button onClick={this.handleClick}>
...
</button>
)
}
// ...
handleClick = () => {
for (let i = 0; i < 5; i++) {
this.setState({ counter: this.state.counter + 1}); // multiple changes to the same state data property are ignored and only the most recent vlaue is applied
} // so the whole for loop is like a single `this.setState({ counter: this.state.counter + 1});`
}
}
I was told that multiple setState
changes to the same state data property are ignored and only the most recent vlaue is applied, so the whole loop above is like a single this.setState({ counter: this.state.counter + 1});
But I'm wondering why React does it in this way? isn't that setState()
just enqueues an unit of work in a "queue", and later React dequeues each work from the queue and applies the change, so even there is 5 times of setState()
call, there will be 5 unit of works in the queue, then React can just dequeue and execute each one, isn't this design is more straightforward and bugs-less?