We write such a piece of code
import React from "react"
export default class App extends React.Component {
constructor(props){
super(props);
this.state = {
cont: 0
}
}
componentDidMount() {
this.setState({
cont: this.state.cont+1
})
}
render(){
return (
<div>
{
this.state.cont }
</div>
)
}
}
We defined a cont value in the state with a value of 0, and then added one to it in the life cycle executed after the first rendering of the componentDidMount page, and then we ran the code. That’s right, it was 0 at the beginning
. It is no problem to become 1, then we change the code of componentDidMount to this and
add it a few more times
, but after running, we will be surprised to find that it is still 1
because the setState function is executed asynchronously, so it is equivalent to the this.state they received. Cont is all 0, then 0 plus one is naturally 1,
so it is equivalent to giving the same value three times
So to solve this problem we can write
import React from "react"
export default class App extends React.Component {
constructor(props){
super(props);
this.state = {
cont: 0
}
}
componentDidMount() {
console.log("componentDidMount");
this.setState((proState,props) => ({
cont: proState.cont+1,
}))
this.setState((proState,props) => ({
cont: proState.cont+1
}))
this.setState((proState,props) => ({
cont: proState.cont+1
}))
}
render(){
return (
<div>
{
this.state.cont }
</div>
)
}
}
setState goes directly to the last value
and finally gets 6 because componentDidMount has been executed twice, but at least it has verified that our method solves the problem of asynchronous continuous calls.
Then there is another problem. We changed the code of componentDidMount to this
componentDidMount() {
this.setState({
cont: this.state.cont+1
})
console.log(this.state.cont);
}
That's the same problem, because setState is asynchronous, so you will definitely not get the latest value if you print after this
we changed it to this
componentDidMount() {
this.setState({
cont: this.state.cont+1
}, () => {
console.log(this.state.cont);
})
}
setState actually provides a callback after the modification is completed,
we can return to the output