如何在React Native中使用AsyncStorage正确获取Item? [英] How to properly getItem with AsyncStorage in React Native?

查看:260
本文介绍了如何在React Native中使用AsyncStorage正确获取Item?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前的项目要求我在本地存储用户数据,因此我使用React Native本身的AsyncStorage.但是我在如何检索已经保存的数据时遇到了一些问题,但我总是会得到null,但是却以某种方式保存了数据.

My current project require me to store user data locally, So I use the AsyncStorage from react native itself. However I got some issues on how to retrieve already saved data I always get null but somehow the data is saved..

我总是

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

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

这是我的代码,这是react native文档中的简单示例

and here's my code, which is the simple example from react native documentation

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

推荐答案

阅读

静态getItem(键,回调?) 获取键的项目,并在完成时调用回调.返回一个Promise对象.

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

您需要兑现承诺.我建议您使用(作为文档)async/await.因此,例如,您可以执行以下操作:

You need to handle that promise. I'd recommend you to use (as the docs) async/await. So for example you can do:

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

您实际上也应该对setItem做类似的事情.

You should actually do something similar for setItem too.

这篇关于如何在React Native中使用AsyncStorage正确获取Item?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆