如何处理this.state的异步性
How to deal with this.state's asynchronicity
这样做:
onPress={() => {
this.setState({
myArray: []
});
const { myArray } = this.state;
console.log(myArray);
}}
预期数组为空,但它仍然包含旧值。如果我再次按下按钮,或者在程序的不同位置按下 console.log,则数组为空。我认为这是由于 this.state 是异步的。这是一个问题,因为我打算像这样将数组保存到 AsyncStore
,而不是 console.log:
AsyncStorage.setItem(
"@ShoppingListStore: ShoppingListKey",
JSON.stringify(myArray)
);
设置状态后无法直接保存数组,请问哪里可以保存?有没有办法监听状态完成设置,然后 运行 AsyncStore 代码?
尝试这样的事情:
onPress={() => {
this.setState({
...this.state, myArray: []
}, () => console.log(this.state.myArray));
}}
这样做:
onPress={() => {
this.setState({
myArray: []
});
const { myArray } = this.state;
console.log(myArray);
}}
预期数组为空,但它仍然包含旧值。如果我再次按下按钮,或者在程序的不同位置按下 console.log,则数组为空。我认为这是由于 this.state 是异步的。这是一个问题,因为我打算像这样将数组保存到 AsyncStore
,而不是 console.log:
AsyncStorage.setItem(
"@ShoppingListStore: ShoppingListKey",
JSON.stringify(myArray)
);
设置状态后无法直接保存数组,请问哪里可以保存?有没有办法监听状态完成设置,然后 运行 AsyncStore 代码?
尝试这样的事情:
onPress={() => {
this.setState({
...this.state, myArray: []
}, () => console.log(this.state.myArray));
}}