I\'m new to React, just have a question on setState method. Let\'s say we have a component:
class MyApp extends React.Component {
state = {
count: 3
If you call a function multiple times to change the value of a state property in a single render() function call then the updated value will not go over between the different calls without prevState mechanism.
second(){
this.setState({ // no previous or latest old state passed
sec:this.state.sec + 1
}, ()=>{
console.log("Callback value", this.state.sec)
})
}
fiveSecJump(){ // all this 5 call will call together
this.second() // this call found sec = 0 then it will update sec = 0 +1
this.second() // this call found sec = 0 then it will update sec = 0 +1
this.second() // this call found sec = 0 then it will update sec = 0 +1
this.second() // this call found sec = 0 then it will update sec = 0 +1
this.second() // this call found sec = 0 then it will update sec = 0 +1
}
render() {
return (
Count - {this.state.sec}
)
}
Finally sec value will be 1, because calls are async, not like high-level programming language like c++/c# or java where there is always a main function which maintains the main thread.
Therefore if you want to have fiveSecJump() function to work properly you have to help it by passing it an arrow function. prevState. prevState is not a keyword or member function, you can write any word here like oldState, stackTopState, lastState. It will convert to a generic function which will do your desired work.
class Counter extends Component {
constructor(props){
super(props)
this.state = {
sec:0
}
}
second(){
this.setState(prevState =>({
sec:prevState.sec + 1
}))
}
fiveSecJump(){
this.second() // this call found sec = 0 then it will update sec = 0 +1
this.second() // this call found sec = 1 then it will update sec = 1 +1
this.second() // this call found sec = 2 then it will update sec = 2 +1
this.second() // this call found sec = 3 then it will update sec = 3 +1
this.second() // this call found sec = 4 then it will update sec = 4 +1
}
render() {
return (
Count - {this.state.sec}
)
}
}
export default Counter