首页 > 解决方案 > 在 react native 中使用 setState 获取更新的值

问题描述

**

我有一个 TextInput 和两个按钮,它们负责增加或减少该 TextInput 的值。使用 setState 我正在实现它。一切都很好,但是在 setState 之后,当我安慰值时,它向我显示了以前的值,但是在 TextInput 中,我得到了更新的值。代码如下: -

**

state = {
    cartItems:[
        {
            id:1,
            count:0
        },
        {
            id:2,
            count:0
        },

    ],
}

changeQuantity = (productId,action)=>{
        this.setState(prevState=>{
            return{
                cartItems:prevState.cartItems.filter(single=>{
                    if(single.id==productId){
                        if(action==='plus'){
                            single.count++;
                        }
                        if(action==='minus' && single.count>0){
                            single.count--;
                        }
                    }
                    return single;
                })
            }

        })
        console.log(this.state.cartItems.find(single => single.id === productId).count) 

/*This gives the previous value not the updated value*/

    }

为什么会发生这种情况,获取更新值的正确方法是什么?

标签: react-nativesetstate

解决方案


setState 是异步的。您编写 console.log 的地方仍然有以前的值,因此它会显示旧值。尝试在 setState 完成块中添加控制台以打印状态的更新值。

this.setState({
  // update your state here 
}, () => {
  console.log('Updated value ');
});

推荐阅读