React Native Async Storage 设置项函数

React Native Async Storage set item function

我在我的项目列表应用程序中使用异步存储。我面临的问题是,在输入第二项之前,我的第一项不会存储在异步中。我在反应挂钩的帮助下保存对象数组 例如,如果我将项目输入为 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()
      }, [])

saveData 函数在提交文本框时调用的 additems 函数中被调用

有一个开源库react-native-easy-app, which wraps the use of AsyncStorage, through which you can access any data in AsncStorage synchronously, maybe it can solve your problem, there is sample program below, maybe you can refer to it. code

您忘记等待清除数据。它本质上也是异步的。

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