I am new to React, and I have a question of set state, this is the code:
this.setState((prevState) => {
return{
prevVal: prevState.currentVal,
currentVal: 'DIGIT LIMIT MET'
}
});
In this code, the prevVal in my project will be updated to 'DIGIT LIMIT MET', but I want it to be the last currentVal which is prevState.currentVal.
this.setState({
prevVal: this.state.currentVal,
currentVal: 'DIGIT LIMIT MET'
});
In this code , the problem will not appear, but according to React document, it can not make sure that the this.state.currentVal is the prevState.currentVal.
How to solve this problem perfectly? Am I misunderstanding something?
this.setState(
prevState => {
const prev = prevState.currentVal;
return {
prevVal: prev,
currentVal: 'DIGIT LIMIT MET'
};
},
() => console.log(this.state)
);
try this.