我正在使用异步存储在React Native中实现登录。在这里,当用户成功登录时,我将用户对象保留在异步存储中,然后在我想执行请求时访问此信息以获取API请求的身份验证密钥。 当我登录并将信息存储在异步存储中时,当前应用程序会话无法获取刚刚存储的信息,因此我所有已认证的请求在此会话中均失败。关闭应用程序并重新启动时,我可以从上一个会话中存储的异步存储中成功获取信息,并进行成功的身份验证请求。
我不知道代码中缺少什么,因为我认为成功登录后需要在内部刷新或重新加载应用程序,但是我不知道如何在React Native中做到这一点。需要任何信息或帮助。这是我的登录代码。
HttpRequest.post('api/login', body)
.then((response) => response.json())
.then((responseJson) => {
if(responseJson.succcode == 201){ //successful login
var data = responseJson.user;
data.loggedIn = true;
AsyncStorage.setItem(USER_DATA, JSON.stringify(data)).then(val => {
console.log('just before reload in login')
Actions.menu(); //this solves the after login problem as it goes to the next page only after a successful AsyncStorage save
this.setState({ procesing: false });
})
.catch(err => {
this.setState({ procesing: false, error: "Couldn't log you in! Please try again" });
//console.log("\nCouldn't save to AsyncStorage: " + err + "\n");
});
}
else{
this.setState({ procesing: false, error: "Wrong Username and/or Password! Please try again" });
}
登录后,我的请求看起来像;
//for making a post request
post: (url,body) => {
return fetch(url+'?access-token='+this.state.user.auth_key, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
//'Autorization': 'Bearer token2'
},
})
,但用户对象是通过
从异步存储中获取的getUser(){
return AsyncStorage.getItem("USER_DATA").then(value => {
if(JSON.parse(value) == null) {
return false;
} else {
return JSON.parse(value)
}
});
},
任何信息,想法,建议的解决方案都将受到欢迎
答案 0 :(得分:0)
如果您正确接收了信息,则可以将信息传递到下一个屏幕,或使用现在的异步存储库。
如果使用导航
HttpRequest.post('api/login', body)
.then((response) => response.json())
.then((responseJson) => {
if(responseJson.succcode == 201){ //successful login
var data = responseJson.user;
data.loggedIn = true;
this.setState({ procesing: false });
this.navigation.navigate("LoginScreen",{data: JSON.stringify(data) })
}
else{
this.setState({ procesing: false, error: "Wrong Username and/or Password! Please try again" });
}
登录屏幕
this.state={
data : this.props.navigation.state.params.data
}
如果使用AsyncStorge
HttpRequest.post('api/login', body)
.then((response) => response.json())
.then((responseJson) => {
if(responseJson.succcode == 201){ //successful login
var data = responseJson.user;
data.loggedIn = true;
AsyncStorage.setItem("USER_DATA", JSON.stringify(data));
this.setState({ procesing: false });
else{
this.setState({ procesing: false, error: "Wrong Username and/or Password! Please try again" });
}
LoginScreen
async componentDidMount() {
let data = await AsyncStorage.getItem("USER_DATA")
}