javascript - 如何使用 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,
}
为什么它不返回我提供的用户名?
在此先感谢,我希望我的问题措辞正确。
解决方案
首先,AsyncStorage
是迁移react-native
到react-native-community
.
您需要从那里安装它。
这是文档和指南。
现在要使用它,您需要使用method
orfunction
async
并使用await
关键字来等待结果。
看到这个,
获取数据 =>
getData=async()=>{ //async is needed to use await
let data = await AsyncStorage.getItem("yourKey")
}
与存储数据的方式相同。
推荐阅读
- reactjs - Reactjs中的天气状态如何
即使“承诺”已完成,组件仍未定义? - android - 无法从 onCreate 外部将数据设置为 MPAndroidChart
- javascript - 使用react js的渲染功能时出错
- laravel - 在 Laravel 5.8 中对多个字段进行唯一验证
- spring - 从同一浏览器访问 API 时获取多个会话对象
- php - 如何使用复选框在 laravel 中存储 foreach 值
- php - Laravel API 测试 - 浏览器和 PHPUnit 之间的 http 请求不同的 baseUrl 和 pathInfo
- angular - 怎么做
点击输入时显示 - javascript - Sync-gateway 返回此错误 401 Login required 是什么意思?
- android - org.json.JSONException:java.lang.String 类型的值成功无法转换为 JSONObject