【发布时间】:2020-05-25 16:16:06
【问题描述】:
import React, { Component } from 'react'
import { Container, Content, Form, Item, Input, Label, Button,Text, Icon} from 'native-base'
import AsyncStorage from '@react-native-community/async-storage';
import authStore from '../store/authStore';
export default class Login extends Component {
constructor(props){
super(props);
this.state={
email:'',
password:''
}
}
handleLogin = async () =>{
let requestObject = {
email: this.state.email,
password: this.state.password
}
authStore.userLogin(requestObject, response => {
this.storeUserData(response.data.data);
this.props.navigation.navigate('Home');
})
}
storeUserData = async (value) => {
try {
const jsonValue = JSON.stringify(value)
await AsyncStorage.setItem('@userData', jsonValue)
} catch (e) {
console.log(e);
}
}
render() {
return (
<Container>
<Content contentContainerStyle={{flex: 1, justifyContent:'center'}}>
<Form style={{margin:10}}>
<Item rounded last style={{margin:10}}>
<Icon active type="FontAwesome" name='user' />
<Input placeholder='User Name'
onChangeText={(email)=>this.setState({email})}
value={this.state.email}/>
</Item>
<Item rounded last style={{margin:10}}>
<Icon active type="FontAwesome" name='key' />
<Input placeholder='Password'
secureTextEntry
onChangeText={(password)=>this.setState({password})}
value={this.state.password}/>
</Item>
<Button rounded block style={{margin:10}} onPress={() => this.handleLogin()}>
<Text>Sign-In</Text>
</Button>
</Form>
</Content>
</Container>
)
}
}
const AuthStack = createStackNavigator();
AuthStackScreen = () =>
<AuthStack.Navigator>
<AuthStack.Screen name="Login" component={Login} />
</AuthStack.Navigator>
HomeStackScreen = () =>
<HomeStackDrawer.Navigator>
<HomeStackDrawer.Screen name="Home" component={HomeScreen}/>
<HomeStackDrawer.Screen name="Form" component={FormScreen}/>
<HomeStackDrawer.Screen name="Logout" component={Logout}/>
</HomeStackDrawer.Navigator>
export default class App extends Component{
constructor(props){
super(props);
this.state={
isloggedIn:false
}
this.loginStatusCheck();
}
loginStatusCheck = async () =>{
const userToken = await AsyncStorage.getItem('@accessToken');
if (userToken) {
this.setState({isloggedIn:true})
} else {
this.setState({isloggedIn:false})
}
}
render(){
return(
<NavigationContainer>
{this.state.isloggedIn ? <HomeStackScreen/> : <AuthStackScreen/>}
</NavigationContainer>
)
}
}
这是我的 App.js,我正在检查用户是否登录,然后相应地加载导航堆栈。我知道问题所在,如果我注销,我想导航到登录组件,但 this.props.navigation.navigate('Login') 给出错误。因为我没有返回Login 路线。如何解决这个问题?另外,当我Log in 出现同样的问题时,因为堆栈中不存在Login。
提前谢谢你
包含登录组件
【问题讨论】:
-
为什么要使用导航返回登录?将根据您所在状态的 isLogged 呈现正确的堆栈
-
这里的逻辑是打开应用时检查。但是如果用户没有登录,登录组件就会被渲染。现在,从 Login 组件,应用程序应该导航到 Home。该怎么做?
标签: react-native react-navigation