如果状态条件处于 Stack.Navigator,则导航找不到屏幕

Navigation can't find screen if states condition is in Stack.Navigator

当我想从主屏幕导航到登录屏幕时出现错误:

ExceptionsManager.js:173 The action 'NAVIGATE' with payload {"name":"Login"} was not handled by any navigator. Do you have a screen named 'Login'?

routes.js:

import LoginScreen from '../screens/login/login';
import HomeScreen from '../screens/home/home';


const Stack = createStackNavigator();

const App = () => {
  const [userToken, setuserToken] = React.useState(null);

  React.useEffect(() => {
    _bootstrapAsync = async () => {      
      const token = await AsyncStorage.getItem('token');    

      if (userToken) { 
        setuserToken(token)
      } 

    }
    _bootstrapAsync()
  })    

  return (
    <NavigationContainer>
      <Stack.Navigator>
        {userToken == null ? (
          <Stack.Screen name="Login" component={LoginScreen} />
         ) : ( 
            <Stack.Screen name="Home" component={HomeScreen} />
         )} 
      </Stack.Navigator>
    </NavigationContainer>
  );

}

export default App;

home.js:

import { AsyncStorage } from 'react-native';
import { Container, Text, Button, Content } from 'native-base';

const HomeScreen = (props) => {
  const { navigation } = props

  handleLogout = async () => {
    await AsyncStorage.clear();
    navigation.navigate('Login');
  };

    return (
      <Container>
        <Content>
          <Button full onPress={handleLogout}>
            <Text>Log Out</Text>
          </Button>
        </Content>
      </Container>
    );

}

export default HomeScreen;

如果在 routes.js 中我删除了 userToken 状态条件,并且在 Stack.Navigator 中只有:

  <Stack.Navigator>
      <Stack.Screen name="Login" component={LoginScreen} />
      <Stack.Screen name="Home" component={HomeScreen} />
  </Stack.Navigator>

我可以成功地从主页导航到登录屏幕。 但是这种方法不好,因为我需要检查存储中是否存在令牌。

我该如何解决这个问题?

在您的条件为真之前,您将无法找到登录路由,这就是您无法找到登录路由的原因

改变

{userToken == null ? (
          <Stack.Screen name="Login" component={LoginScreen} />
         ) : ( 
            <Stack.Screen name="Home" component={HomeScreen} />
         )} 

to

{userToken == null ? (
          <Stack.Screen name="Login" component={LoginScreen} />
         ) : ( 
            <Stack.Screen name="Home" component={HomeScreen} />
            <Stack.Screen name="Login" component={LoginScreen} />
         )} 

希望对您有所帮助!