【问题标题】:React Native Async Storage set item functionReact Native Async Storage 设置项功能
【发布时间】: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


【解决方案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

【讨论】:

  • 是的,我在 AddItem 函数中使用 await 和 await setWant() 修复了它。不过谢谢:)
【解决方案2】:

有一个开源库react-native-easy-app,封装了AsyncStorage的使用,通过它你可以同步访问AsncStorage中的任何数据,或许可以解决你的问题,下面有sample的程序,或许你可以参考给它。 code.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    相关资源
    最近更新 更多