我正在尝试使用异步存储来存储数组,然后在用户单击将其引导到页面的按钮时更新该数组,这就是为什么我使用“ useEffect”的原因。但是,我的问题是,当我尝试进行console.log记录时,该数组始终为空。我正在做的是当需要调用setItem时,我首先获得了该项目的当前值,追加了我想要设置的值,然后设置了该项目,这样数组就被更新了并且不会被覆盖,但这不是工作。
const paymentValue = [
{
"startingLocation": startingLocation,
"endingLocation": endingLocation,
"departure": departure,
"timeFormat": timeFormat,
"receiptNo": receiptNo
}
]
const storeData = async (value: any) => {
try {
const paymentsInfo = await AsyncStorage.getItem('payments')
const obj: never[] = []
if (paymentsInfo != null){
const obj = JSON.parse(paymentsInfo)
obj.concat(value)
console.log(obj)
}
const jsonValue = JSON.stringify(obj)
await AsyncStorage.setItem('payments', jsonValue)
} catch (e) {
console.log(e)
}
}
const getData = async () => {
try {
const paymentsInfo = await AsyncStorage.getItem('payments')
if (paymentsInfo !== null) {
console.log(JSON.parse(paymentsInfo))
}
} catch(e) {
console.log(e)
}
}
React.useEffect(() => {
storeData(paymentValue)
getData()
})