如何在 React Native 中使用 AsyncStorage 正确获取 Item?

How to properly getItem with AsyncStorage in React Native?

我目前的项目需要我在本地存储用户数据,所以我使用了 React Native 本身的 AsyncStorage。但是我在如何检索已保存的数据方面遇到了一些问题我总是得到 null 但不知何故数据被保存了..

我总是

{ _45: 0, _81: 0, _65: null, _54: null }

这是我的代码,这是来自 React Native 文档的简单示例

AsyncStorage.setItem('baru', 'this is new dude!!');
var b = AsyncStorage.getItem('baru');
console.log(b);

正在阅读 AsyncStorage 的文档:

static getItem(key, callback?) Fetches an item for a key and invokes a callback upon completion. Returns a Promise object.

你需要兑现这个承诺。我建议您使用(作为文档)async/await。例如,您可以这样做:

async function getItem(item) {
  try {
    const value = await AsyncStorage.getItem(item);
    console.log(value);
    return value;
  } catch (error) {
    // Handle errors here
  }
}

你实际上也应该为 setItem 做类似的事情。