【问题标题】:AsyncStorage setItem/getItem not working?AsyncStorage setItem/getItem 不工作?
【发布时间】:2017-11-07 19:23:53
【问题描述】:

我正在使用 AsyncStorage 在应用程序中存储和检索一些信息(如姓名、电子邮件)。当我调用 setItem 它返回承诺 "_45":0,"_65":0,"_55":null:"_75":null 和 getItem 也返回相同。如何设置/获取 AsyncStorage 中的值? 我正在使用以下代码:

export async function setItem(key, value) {
  try {
    var data = await AsyncStorage.setItem(key, value);
  } catch (error) {

  }
}

export async function getItem(key) {
  try {
    var item = await AsyncStorage.getItem(key);
    if(item !== null) {
      return item;
    }
  } catch (error) {

  }
}

提前致谢。

【问题讨论】:

    标签: javascript react-native asyncstorage


    【解决方案1】:

    您的函数返回承诺。 async/await 只是一个语法糖。如果你想使用你的助手从AsyncStorage 获取项目,你需要这样使用:

    getItem('someKey')
      .then(val => console.log(val)
      .catch(err => console.log(err))
    

    function async getItemAndDoSomething() {
      const item = await getItem('someKey')
      // do something with your item here
    }
    
    getItemAndDoSomething()
    

    【讨论】:

    • 但它会返回如下 "_45":0,"_65":0,"_55":MyExpectedValue,"_75":null 。我如何访问我使用 _55 或任何其他方式访问的值?
    【解决方案2】:

    async 函数的返回值包含在一个 Promise 中。在您的 getItem 中,您可以将 item 作为标准对象访问,但 getItem 的调用者需要 (1) 是异步函数或 (2) 将返回值视为 Promise。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多