Answer the question
In order to leave comments, you need to log in
Why is the old value of state displayed?
Why console.log
does it display the old value from state if setState worked before?
import React, {Component} from "react";
export default class Test extends Component{
constructor(props) {
super(props);
this.state = {
test: false
}
}
componentWillMount() {
this.setState({
test: !this.state.test
});
console.log(this.state.test)//false
}
render() {
return (
<div />
)
}
}
Answer the question
In order to leave comments, you need to log in
Becausethis.props
andthis.state
may be updated asynchronously, you should not rely on their values for calculating the next state.
this.setState(
(state) => ({test: !state.test}),
() => console.log(this.state.test)
);
this.setState(
prevState => ({ test: !prevState.test }),
() => console.log(this.state.test),
);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question