console.log
выводит старое значение из state, если перед этим сработал setState?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 />
)
}
}
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)
);