且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

反应本地登录和登录导航-正确的方式建议

更新时间:2023-12-05 11:37:04

推荐的***做法是只有一个NavigationContainer。我认为所有导航状态都有一个真实来源很重要。

尝试如下重构代码:

export default function App() {
  //shared states
  const { loggedInUser, setLoggedInUser } = useBetween(useLoggedInUserState);

  //common states
  const [loading, setLoading] = useState(false);

  //check storage and store user in state
  useEffect(async () => {
    setLoading(true);
    const objUser = await getLoggedInUser();
    setLoggedInUser(objUser);
    setLoading(false);
  }, []);

  //render
  return !loading ? (
    <NavigationContainer>
      {loggedInUser ? (
        <Drawer.Navigator
          drawerContent={(drawerContentProps) => (
            <Sidebar
              loggedInUser={propsLoggedIn.loggedInUser}
              {...drawerContentProps}
            />
          )}
        >
          <Drawer.Screen
            name="Dashboard"
            component={BottomNav}
            initialParams={{ title: "Dashboard" }}
          />
          <Drawer.Screen
            name="About"
            component={AboutScreen}
            initialParams={{ title: "About" }}
          />
          <Drawer.Screen
            name="Terms"
            component={TermsScreen}
            initialParams={{ title: "Terms" }}
          />
          <Drawer.Screen
            name="VehicleEdit"
            component={VehicleEditScreen}
            initialParams={{ title: "Edit Vehicle" }}
          />
          <Drawer.Screen
            name="Cart"
            component={CartScreen}
            initialParams={{ title: "Cart" }}
            options={{ drawerItemStyle: { display: "none" } }}
          />
          <Drawer.Screen
            name="Payment"
            component={PaymentScreen}
            initialParams={{ title: "Payment" }}
            options={{ drawerItemStyle: { display: "none" } }}
          />
          <Drawer.Screen
            name="NotificationTest"
            component={NotificationTestScreen}
            initialParams={{ title: "NotificationTest" }}
            options={{ drawerItemStyle: { display: "none" } }}
          />
        </Drawer.Navigator>
      ) : (
        <Stack.Navigator
          screenOptions={{
            headerShown: false,
          }}
          initialRouteName="Home"
        >
          <Stack.Screen name="Home" component={HomeScreen} />
          <Stack.Screen name="Login" component={LoginScreen} />
          <Stack.Screen name="Register" component={RegisterScreen} />
          <Stack.Screen
            name="ForgotPassword"
            component={ForgotPasswordScreen}
          />
          <Stack.Screen name="Dashboard" component={DashboardScreen} />
        </Stack.Navigator>
      )}
    </NavigationContainer>
  ) : (
    <View>
      <Text>Loading...</Text>
    </View>
  );
}