如何在React-Navigation V5中动态显示抽屉项目?

问题描述 投票:0回答:1

尝试在React-Navigation抽屉中动态显示不同的项目时,我有些麻烦。

如果用户未登录,我有一个抽屉,需要显示其他项目。在这种情况下,如果用户已登录,则不应显示“ RegisterScreen”和“ LoginScreen”按钮,而应显示“ Log Out”按钮。但是,如果用户未登录,则应同时显示“注册”和“登录”屏幕,而不应显示“注销”按钮。

我已经使用下面的代码成功显示了按钮(除了“注销”按钮,我还没有这样做)。但是,一旦用户注销,应用程序会将其重定向到登录屏幕。由于我没有在抽屉中声明它们,因此出现以下错误:

console.error: The action 'NAVIGATE' with payload {"name":"LoginModal"} was not handled by any navigator.

我知道没有添加屏幕,但是我不知道当用户登录时如何隐藏它们。

代码:

//Added DrawerItemList for the Logout button.
  const CustomDrawerContent = (props) => {
    return (
      <DrawerContentScrollView {...props}>

        <DrawerItemList {...props} />
        <DrawerItem
          label="Logout"
          onPress={async () => {
            props.navigation.closeDrawer();
            await LogOut().then((result) => {
              props.navigation.navigate('LoginModal');
            });
          }}
        />

      </DrawerContentScrollView>
    );
  };

  const [drawerCategories, setDrawerCategories] = useState([]);

//Checks if the user is logged in and sets Login and Register screens in the state.
  useEffect(() => {
    let mounted = true;
    if (mounted) {
      AsyncStorage.getItem('userId').then((result) => {
        console.log(result);
        if (result == null) {
          setDrawerCategories([
            ...drawerCategories,
            {name: 'LoginModal', component: {LoginScreen}},
            {name: 'RegisterModal', component: {RegisterScreen}},
          ]);
        }
      });
    }
    return () => (mounted = false);
  }, []);

  return (
    <NavigationContainer>
      <RootDrawer.Navigator
        drawerType="front"
        initialRouteName="Home"
        mode="modal"
        drawerContent={(props) => <CustomDrawerContent {...props} />}>
        <RootDrawer.Screen name="Home" component={MainStackScreen} />

//Add the Register and Login buttons here
        {drawerCategories.map((drawer) => {
          <RootDrawer.Screen name={drawer.name} component={drawer.component} />;
        })}

      </RootDrawer.Navigator>
    </NavigationContainer>
  );

您能帮我弄清楚如何解决此错误吗?非常感谢!

reactjs react-native react-navigation react-navigation-v5 react-navigation-drawer
1个回答
0
投票

不确定LogOut函数的作用,但是除非它实际上重新运行了效果以便定义了LoginModal屏幕,否则将不会有名为LoginModal的屏幕进行导航。

查看您的代码,注销后将不会重新运行您的效果。而不是设置效果中的屏幕列表,您应该将代码安排为如下所示:

  1. 全局存储,例如Redux,React Context或您更喜欢存储userId的任何东西
  2. useEffect钩子应该还原,尝试像现在一样从userId还原AsyncStorage,但是还原后,它应该更新全局存储以更新那里的userId,而不是设置屏幕。] >
  3. 您的logOut功能应从userId中删除AsyncStorage并更新全局存储,以使其为null
  4. 在组件内部,应根据userId是否为null有条件地定义屏幕,并且它们将在登录或注销时自动更改
  5. 认证流程的文档显示了如何使用令牌和堆栈导航器进行操作的示例:https://reactnavigation.org/docs/auth-flow/

您可以对用户ID和抽屉式导航器使用类似的策略。

© www.soinside.com 2019 - 2024. All rights reserved.