**
我有一个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*/
}
为什么会这样?获取更新值的正确方法是什么?
答案 0 :(得分:3)
setState是异步的。您编写console.log的位置仍将具有先前的值,因此它将显示您的旧值。尝试在setState完成块中添加控制台以打印状态的更新值。
this.setState({
// update your state here
}, () => {
console.log('Updated value ');
});
答案 1 :(得分:1)
在调用setState之后,您将控制台转到下一行 将仅记录以前的状态。我不知道为什么这种行为存在。尝试将其记录在componentDidUpdate中。