【问题标题】:Navigation can't find screen if states condition is in Stack.Navigator如果状态条件在 Stack.Navigator 中,则导航找不到屏幕
【发布时间】:2020-04-28 07:21:35
【问题描述】:

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

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 为真,您将拥有一个名为 login 的路由,但在这种情况下,当您在主屏幕中时,您将无法导航到登录屏幕,因为条件为假.

标签: react-native navigation


【解决方案1】:

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

改变

{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} />
         )} 

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2018-06-05
    • 2021-07-21
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多