如何使用redux-persist react native保护经过身份验证的路由

wlzqhblo  于 2023-05-18  发布在  React
关注(0)|答案(1)|浏览(146)

我试图在react原生应用程序中使用redux-persistent和redux-toolkit来保护经过验证的路由。我以为这就像使用选择器访问存储或状态一样简单,以检查我的令牌是否为空,然后有条件地呈现不同的屏幕,但它只抛出两个错误:“上述错误发生在组件:“和““未捕获的TypeError:配置未定义””
这是我的App.tsx文件。我有一个持有jwt的身份验证状态,如果它是空的,我想封锁其他路由。我不知道该怎么做。

import { createNativeStackNavigator } from "@react-navigation/native-stack";
import { NavigationContainer } from "@react-navigation/native";
import React from "react";
import HomeScreen from "./src/screens/home";
import Register from "./src/screens/register";
import Feed from "./src/screens/feed";
import Login from "./src/screens/login";
import { Text } from "react-native";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { StatusBar } from "expo-status-bar";
import { NativeBaseProvider } from "native-base";
import customTheme from "./src/shared/theme";
import { Provider } from "react-redux";
import { persistor, store } from "./src/store/store";
import { PersistGate } from "redux-persist/integration/react";
import ProfileScreen from "./src/screens/Profile";

const Stack = createNativeStackNavigator();

//web links
const linking = {
  prefixes: [],
  config: {
    screens: {
      Login: "login",
      Register: "register",
      Profile: "profile",
      Home: "home",
      Feed: "feed",
    },
  },
};

export default function App() {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <SafeAreaProvider>
          <NativeBaseProvider theme={customTheme}>
            <NavigationContainer
              linking={linking}
              fallback={<Text>Something went wrong...</Text>}
            >
              <Stack.Navigator
                initialRouteName="Login"
                screenOptions={{
                  headerShown: false,
                  animation: "none",
                  gestureEnabled: false,
                }}
              >
                {/* what do I do here: I get an error... */}
                {store.getState().auth.jwt === "" ? (
                  <>
                    <Stack.Screen name="Login" component={Login} />
                    <Stack.Screen name="Register" component={Register} />
                  </>
                ) : (
                  <>
                    <Stack.Screen name="Home" component={HomeScreen} />
                    <Stack.Screen name="Profile" component={ProfileScreen} />
                    <Stack.Screen name="Feed" component={Feed} />
                  </>
                )}
              </Stack.Navigator>
            </NavigationContainer>
          </NativeBaseProvider>
          <StatusBar />
        </SafeAreaProvider>
      </PersistGate>
    </Provider>
  );
}

我试过使用store.getState().auth.jwt === "",但它抛出了一个错误“Uncatch TypeError:配置未定义”

o4hqfura

o4hqfura1#

通过将PersistGate下面的所有内容移动到一个新函数中并在那里使用常规选择器来获取我的auth令牌并像我一样有条件地呈现来修复此问题。
也有条件地声明了initialRouteName。

相关问题