react native中的反应导航,带有条件堆栈和认证

问题描述 投票:0回答:1
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没有出现在堆栈中。预先谢谢你

react-native react-navigation
1个回答
0
投票

您可以使用ActivityIndi​​cator,直到从AsynStorage加载值为止。这将显示一个加载屏幕,直到loginIn值加载到该状态。像这样的东西

export default class App1 extends Component{
  constructor(props){
    super(props);
    this.state={
      isloggedIn:false,
      loading:true
    }
    this.loginStatusCheck();
  }
  loginStatusCheck = async () =>{
    const userToken = await AsyncStorage.getItem('@accessToken');
    if (userToken) {
      this.setState({isloggedIn:true,loading:false})
    } else {
      this.setState({isloggedIn:false,loading:false})
    }
  }
  render(){
    if(this.state.loading)
     return <ActivityIndicator />;

    return(
      <NavigationContainer>
        {this.state.isloggedIn ? <HomeStackScreen/> : <AuthStackScreen/>}
      </NavigationContainer>
    )
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.