react-native - 异步存储无法在 React Native 上设置或获取

标签 react-native asyncstorage

我试图使用异步存储进行用户身份验证来决定将呈现哪个屏幕,所以当我从异步存储中获取数据时返回给我未定义有人可以帮助我吗?

我的获取代码:

var login;
AsyncStorage.getItem("login").then((value) => {
      login = value;
}).done();
alert(login);

我的设置代码:
const insert_user = (username) => {
  AsyncStorage.setItem("login", username);
  Toast.show({
    supportedOrientations: ['portrait', 'landscape'],
    text: `User registered with success`,
    position: 'bottom',
    buttonText: 'Dismiss'
  });
}

最佳答案

alert(login);将始终未定义,因为 AsyncStorage.getItem 本质上是异步的,这意味着在您从 AsyncStorage.getItem 接收值之前首先调用 alert(login)

AsyncStorage.getItem("login").then((value) => {
      alert(value); // you will need use the alert in here because this is the point in the execution which you receive the value from getItem.
    // you could do your authentication and routing logic here but I suggest that you place them in another function and just pass the function as seen in the example below.
});

// a function that receives value
const receiveLoginDetails = (value) => {
    alert(value);
}
// pass the function that receives the login details;
AsyncStorage.getItem("login").then(receiveLoginDetails);

进一步引用
  • AsyncStorage.getItem 将返回一个 Promise:https://www.promisejs.org/
  • 异步与同步:https://www.pluralsight.com/guides/front-end-javascript/introduction-to-asynchronous-javascript
  • 关于react-native - 异步存储无法在 React Native 上设置或获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45341020/

    相关文章:

    react-native - React Native 的异步存储安全吗?

    react-native - 如何在 AsyncStorage 中存储图像?

    javascript - 如何在 firestore 中离线读取文档并写入(在线和离线)?

    android - 在 React Native 中从 Asyncstorage 数据库获取数据的最佳实践

    android - 在设备中运行 React Native 应用程序

    react-native - react native 防止双击

    react-native - 在使用 redux-persist 存储重新水化之前加载初始状态的默认值

    react-native - React Native - 更新 AsyncStorage 项目嵌套键值?

    javascript - React Native onChangeText 只执行一个函数

    javascript - React Native 无法读取未定义的属性 '0'