react-native - 在 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*/
}
为什么会发生这种情况,获取更新值的正确方法是什么?
解决方案
setState 是异步的。您编写 console.log 的地方仍然有以前的值,因此它会显示旧值。尝试在 setState 完成块中添加控制台以打印状态的更新值。
this.setState({
// update your state here
}, () => {
console.log('Updated value ');
});
推荐阅读
- javascript - 如何检查整个字符串是否与Javascript中的正则表达式匹配?
- azure - azure vm脚本扩展运行直到超时
- java - Docker CMD 中的链节点和 java 命令
- javascript - Javascript“文档”未定义
- java - 无法使用 resttemplate jaxb 解组响应正文
- ios - 切换保存用户首选项
- php - 我想要底部的分页,它显示在右侧
- php - Wampserver gibin 不是 php 5.4 的有效 Win32 应用程序
- android - 从 Android 应用调用 REST 服务的 URL
- android - 如何在导航抽屉中的组标题旁边添加一条水平线?