【发布时间】:2020-10-24 17:02:14
【问题描述】:
这个问题已经回答了,你可以忽略它并点击离开
我正在使用 react native expo 制作我的应用程序,成功登录后,我的服务器返回一个令牌,我想将它存储在 AsyncStorage 中,这是我的代码:
import { Alert, AsyncStorage } from "react-native";
export const login_as_student = async (code, password, navigation) => {
return fetch("http://192.168.47.102:5000/users/login/student", {
// Windows + CMD
// Wireless LAN adapter Wi-Fi
method: "POST",
headers: {
"content-type": "application/json; charset=UTF-8",
},
body: JSON.stringify({ code, password }),
})
.then((response) => {
return response.json();
})
.then((json) => {
const { currentUser, token } = json;
console.log(json);
if (token && currentUser) {
AsyncStorage.setItem("token", token)
.then((value) => console.log("token", value))
.catch((error) => console.log(error));
return navigation.navigate("Darshboard");
} else {
console.log(json);
Alert.alert(json.message);
}
})
.catch((err) => {
console.log(err);
Alert.alert(err.message);
});
};
结果如下:
Object {
"currentUser": Object {
"__v": 0,
"_id": "5f8be6bf0220db23d096ca14",
"activated": false,
"code": "16020503",
"fullname": "Đỗ Xuân An ",
"password": "$2b$10$PQ5EAc3Vkn1WT00uKadYi.ue2UR1lRBfSeF.cXgZps2pqejV4bAUy",
"profileImage": "https://avataaars.io/?accessoriesType=Prescription01&avatarStyle=Circle&clotheColor=Blue02&clotheType=BlazerSwet
er&eyeType=WinkWacky&eyebrowType=FlatNatural&facialHairColor=Platinum&facialHairType=MoustacheFancy&hairColor=Platinum&hatColor=PastelRed&mouthType=Vomit&skinColor=Brown&topType=LongHairMiaWallace",
"role": "student",
"vnumail": "16020503@vnu.edu.vn",
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiXCI1ZjhiZTZiZjAyMjBkYjIzZDA5NmNhMTRcIiIsImlhdCI6MTYwMzU1ODYyOSwiZXhwIjoxNjAzNjQ1MDI5fQ.cxOHxddB_ha94ZGXY_XLcCs1MgDJHhZDgbl4GFOzk80",
}
token null
如您所见,我收到了一个包含 2 个对象的 json,即 token 和 currentUser,之后我将它存储在 AsyncStorage 但它返回 null,我是 React Native 的新手,感谢您帮助我美好的一天:)
更新:
谢谢大家,我发现 AsyncStorage 不再是从“react-native”导入的,它现在是从“@react-native-community/async-storage”导入的,祝你有美好的一天
【问题讨论】:
标签: javascript reactjs react-native asynchronous mobile