设置2个屏幕后,进行反应导航。第一个屏幕上有一个Login(登录),并按下了按钮,从服务器获取令牌。而且,仅当获取和令牌存储时,我才需要导航到另一个屏幕。我在react-navigation文档中发现的只是一个带有按钮和导航标题的解决方案,但这不是这种情况。
我尝试将重定向道具放置在函数中,但没有用。
请问有人有什么备用建议吗?
非常感谢!
这是代码
import React, { Component } from 'react';
import { Text, TextInput, View, StyleSheet, AsyncStorage } from 'react-native';
import { Card, Button, CardSection, Input, Spinner } from '../components';
import { createStackNavigator } from 'react-navigation';
const AUTH_TOKEN = 'auth_token';
class Login extends Component {
constructor() {
super();
this.state = {
email: "",
password: "",
error: ""
}
}
storeToken(responseData){
AsyncStorage.setItem(AUTH_TOKEN, responseData, (err)=> {
if(err){
console.log("Something went wrong");
throw err;
}
console.log("Success");
}).catch((err)=> {
console.log("error is: " + err);
});
}
async onLoginPressed() {
try {
let response = await fetch('https://las.herokuapp.com/api/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
session: {
email: this.state.email,
password: this.state.password,
}
})
});
let res = await response.text();
if (response.status >= 200 && response.status < 300) {
let authToken = res;
console.log(authToken);
this.storeToken(authToken);
SHOULD REDIRECT ----> //this.props.navigation.navigate('Home');
} else {
let error = res;
throw error;
}
} catch (error) {
this.setState({ error: error });
console.log("Error" + error);
}
}
render() {
return (
<Card>
<Text> Login </Text>
<CardSection>
<Input onChangeText = {
(text) => this.setState({ email: text }) }
placeholder = "Email" />
</CardSection>
<CardSection>
<Input onChangeText = {
(text) => this.setState({ password: text }) } secureTextEntry = { true } placeholder = "Password"/>
</CardSection>
<CardSection>
<Button
onPress={this.onLoginPressed.bind(this)}>
Log in
</Button>
</CardSection>
<Text style={styles.error}> { this.state.error } </Text>
</Card>
);
}
}
答案 0 :(得分:0)
您应该在令牌保存后浏览,如下面的代码所示:
storeToken(responseData){
AsyncStorage.setItem(AUTH_TOKEN, responseData, (err)=> {
if(err){
console.log("Something went wrong");
throw err;
} else{
this.props.navigation.navigate('Home');
console.log("Success");
}
}).catch((err)=> {
console.log("error is: " + err);
});
}
主屏幕代码:
render() {
return <View/>
}