Functional Component
const [counter, setCounter] = useState(0);
setCouter(counter + 1);
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
this.setState({
date: new Date()
});
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
@protected
void setState(VoidCallback fn) {
if (_scopeKey.currentState != null) {
_scopeKey.currentState!._routeSetState(fn);
} else {
// The route isn't currently visible, so we don't have to call its setState
// method, but we do still need to call the fn callback, otherwise the state
// in the route won't be updated!
fn();
}
}
incrementCount() {
// Note: this will *not* work as intended.
this.setState({count: this.state.count + 1});
}
handleSomething() {
// Let's say `this.state.count` starts at 0.
this.incrementCount();
this.incrementCount();
this.incrementCount();
// When React re-renders the component, `this.state.count` will be 1, but you expected 3.
// This is because `incrementCount()` function above reads from `this.state.count`,
// but React doesn't update `this.state.count` until the component is re-rendered.
// So `incrementCount()` ends up reading `this.state.count` as 0 every time, and sets it to 1.
// The fix is described below!
}