1class App extends React.Component {
2
3state = { count: 0 }
4
5handleIncrement = () => {
6 this.setState({ count: this.state.count + 1 })
7}
8
9handleDecrement = () => {
10 this.setState({ count: this.state.count - 1 })
11}
12 render() {
13 return (
14 <div>
15 <div>
16 {this.state.count}
17 </div>
18 <button onClick={this.handleIncrement}>Increment by 1</button>
19 <button onClick={this.handleDecrement}>Decrement by 1</button>
20 </div>
21 )
22 }
23}
1Functional Component
2const [counter, setCounter] = useState(0);
3
4setCouter(counter + 1);
1incrementCount() {
2 // Note: this will *not* work as intended.
3 this.setState({count: this.state.count + 1});
4}
5
6handleSomething() {
7 // Let's say `this.state.count` starts at 0.
8 this.incrementCount();
9 this.incrementCount();
10 this.incrementCount();
11 // When React re-renders the component, `this.state.count` will be 1, but you expected 3.
12
13 // This is because `incrementCount()` function above reads from `this.state.count`,
14 // but React doesn't update `this.state.count` until the component is re-rendered.
15 // So `incrementCount()` ends up reading `this.state.count` as 0 every time, and sets it to 1.
16
17 // The fix is described below!
18}
1@protected
2void setState(VoidCallback fn) {
3 if (_scopeKey.currentState != null) {
4 _scopeKey.currentState!._routeSetState(fn);
5 } else {
6 // The route isn't currently visible, so we don't have to call its setState
7 // method, but we do still need to call the fn callback, otherwise the state
8 // in the route won't be updated!
9 fn();
10 }
11}