我可以使用我的用户名和密码(硬编码)登录,但是,登录后我想从 API 中获取一些数据,这只有在我通过身份验证后才能完成。 那么问题来了,如何让用户保持登录状态呢?
我不太擅长 React-Native,所以任何帮助将不胜感激!
这是我的代码:
import React, { Component } from 'react';
import { Text, View, StyleSheet,AsyncStorage, FlatList, AppRegistry } from 'react-native';
import { ListItem } from 'react-native-elements';
export default class BMPServer extends React.Component {
constructor(props) {
super(props);
this.state = {
username: 'testuser',
password: 'mypasswordhere',
signedIn: false,
checkedSignIn: false
};
this.getAllDocuments();
}
getAllDocuments = () => {
fetch('https://example.dk/rest/Login/Authenticate/?businessId=1&solutionId=1', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username : this.state.username,
password : this.state.password,
})
})
.then((response) => response.json())
.then((responseDocs) => {
console.log("YOU HAVE SUCCSFULLY LOGGED IN:", responseDocs)
});}
最佳答案
假设您在身份验证成功后获得了 token 。
import { AsyncStorage } from 'react-native';
fetch('https://example.dk/rest/Login/Authenticate/?businessId=1&solutionId=1', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username : this.state.username,
password : this.state.password,
})
})
.then((response) => AsyncStorage.setItem(LOGIN_TOKEN, response))
.then((responseDocs) => {
console.log("YOU HAVE SUCCSFULLY LOGGED IN:", responseDocs)
});}
所以,现在您已将 token 存储在 asyncstorage 中。因此,例如,在您的初始屏幕上,启动屏幕给出一个条件来检查是否使用
AsyncStorage.getItem(LOGIN_TOKEN);
关于react-native - 如何保持用户登录状态(使用 AsyncStorage 存储 userId),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54908211/