【发布时间】:2021-02-16 12:09:44
【问题描述】:
我在我的项目列表应用程序中使用异步存储。我面临的问题是,在我输入第二个项目之前,我的第一个项目不会存储在异步中。我在反应钩子的帮助下保存了一组对象 例如,如果我输入项目为 1)苹果 2)香蕉 那么只有苹果会被异步保存,而香蕉在我输入第三项之前不会被保存。
const [getWant, setwant] = useState([]);
const saveData = async () => {
AsyncStorage.clear()
try {
await AsyncStorage.setItem("@pantry102", JSON.stringify(getWant))
console.log(getWant)
alert('Data successfully saved')
} catch (e) {
alert('Failed to save the data to the storage')
}
}
const readData = async () => {
try {
const userData= await AsyncStorage.getItem("@pantry102")
const userData2 = JSON.parse(userData)
if (userData2 !== null) {
console.log(userData2)
setwant(userData2)
}
} catch (e) {
alert('Failed to fetch the data from storage')
}
}
useEffect(() => {
readData()
}, [])
在提交文本框时调用的 additems 函数中调用 saveData 函数
【问题讨论】:
-
根据什么输出你说该项目没有得到保存?
-
我使用了 console.log,它在第一次保存时显示空数组,在第二次保存时它包含第一项。此外,当我重新加载应用程序以检查旧保存的数据时,只有第一个项目才会显示,而这两个项目都应该显示。这是我的零食博览会链接snack.expo.io/@moeez71/7f7d44你可以自己测试一下
标签: reactjs react-native async-await asyncstorage