在 React Native 中使用 setState 获取更新值
Get the updated value using setState in react native
**
I have a TextInput and two buttons which are responsible to increment
or decrement the value of that TextInput. Using setState I am achieving
it. Everything is fine but after setState when I am consoling the
value it is showing me the previous value, but in TextInput I am
getting the updated value. The code is the following:-
**
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*/
}
为什么会发生这种情况以及获取更新值的正确方法是什么?
It you do a console to next line after setState has been called it
will log only previous state. I don't know why the behaviour exists. Try logging it in componentDidUpdate.
setState 是异步的。你写 console.log 的地方仍然有以前的值,因此它会显示旧值。尝试在 setState 完成块中添加控制台以打印状态的更新值。
this.setState({
// update your state here
}, () => {
console.log('Updated value ');
});
**
I have a TextInput and two buttons which are responsible to increment or decrement the value of that TextInput. Using setState I am achieving it. Everything is fine but after setState when I am consoling the value it is showing me the previous value, but in TextInput I am getting the updated value. The code is the following:-
**
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*/
}
为什么会发生这种情况以及获取更新值的正确方法是什么?
It you do a console to next line after setState has been called it will log only previous state. I don't know why the behaviour exists. Try logging it in componentDidUpdate.
setState 是异步的。你写 console.log 的地方仍然有以前的值,因此它会显示旧值。尝试在 setState 完成块中添加控制台以打印状态的更新值。
this.setState({
// update your state here
}, () => {
console.log('Updated value ');
});