简体   繁体   English

在 React 中将值设置为 state

[英]set value to state in React

I am new to React, and I have a question of set state, this is the code:我是 React 的新手,我有一个问题集 state,这是代码:

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.在此代码中,我项目中的prevVal将更新为'DIGIT LIMIT MET' ,但我希望它是最后一个currentVal ,即 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.在这段代码中,不会出现这个问题,但是根据React文档,无法确定this.state.currentVal就是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.尝试这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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