我在商品列表应用中使用了异步存储。我面临的问题是,直到我输入第二个项目,我的第一个项目才会存储在异步中。我在反应钩子的帮助下保存对象数组 例如,如果我将项目输入为 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函数
答案 0 :(得分:1)
您忘记等待清除数据。它本质上也是异步的。
await AsyncStorage.clear()
const saveData = async () => {
try {
await AsyncStorage.clear();
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");
}
};
我建议,只需覆盖它即可。无需清除。
了解更多:https://react-native-async-storage.github.io/async-storage/docs/api#clear
:-D
答案 1 :(得分:0)
有一个开放源代码库react-native-easy-app,其中包含AsyncStorage的用法,通过它您可以同步访问AsncStorage中的任何数据,也许可以解决您的问题,下面有sample程序,也许你可以参考一下。 code。