首页 > 解决方案 > 如何使用 AsyncStorage 在 React Native 中保存我的登录凭据?

问题描述

我是 react-native 的新手,似乎无法弄清楚这一点。我可以登录我需要连接的 API,但是我需要弄清楚如何保存登录凭据。

我目前正在为此使用 AsyncStorage,但我可能react-native-secure-key-store很快就会改用它。它不允许我使用它,当我尝试时,它会引发关于 Null 如何不是对象的错误。所以,现在我只使用 AsyncStorage。

这是我目前用来导入 AsyncStorage 的代码:

import { AsyncStorage, Image, StyleSheet, View, Text, Platform } from "react-native";

Login.ts 中保存登录凭据的代码:

console.log("logging user in...")
const username = this.state.username;
const password = this.state.password;
// save the item to AsyncStorage
AsyncStorage.setItem("username", JSON.stringify(username));
console.log(username);

Secured.ts 中获取凭据的代码:

// get item from AsyncStorage
const username = AsyncStorage.getItem("username") || 'none';
// set the state to include the username
this.state = {
  username: username,
};
console.log(this.state.username);

这是我console.log(this.state.username);在 Secured.ts 中得到的信息:

_ {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
}

为什么它不返回我提供的用户名?

在此先感谢,我希望我的问题措辞正确。

标签: javascriptreactjsreact-native

解决方案


首先,AsyncStorage是迁移react-nativereact-native-community.

您需要从那里安装它。

是文档和指南。

现在要使用它,您需要使用methodorfunction async并使用await关键字来等待结果。

看到这个,

获取数据 =>

getData=async()=>{ //async is needed to use await
   let data = await AsyncStorage.getItem("yourKey")
}

与存储数据的方式相同。


推荐阅读