简体   繁体   中英

set value to state in React

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM