[英]How can I use AsyncStorage to save my login credentials in 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
或function
async
並使用await
關鍵字等待結果。
看到這個
獲取數據=>
getData=async()=>{ //async is needed to use await
let data = await AsyncStorage.getItem("yourKey")
}
以相同的方式存儲數據。
這是因為所有AsyncStorage方法都返回了Promise,因此您應該等待響應。
一種方法是只放置await
關鍵字
await AsyncStorage.setItem("username", JSON.stringify(username));
// ...
const username = await AsyncStorage.getItem("username") || 'none';
並且您應該能夠獲得用戶名。
如果您不知道什么是Promises,請閱讀一些文檔:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise#Examples
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.