react native中的异步条件组件渲染

时间:2021-05-01 15:25:26

标签: react-native react-navigation

我正在尝试在我的 RN 应用程序中设置前端身份验证系统,但在呈现身份验证视图或主应用程序视图时遇到问题。

根导航器呈现身份验证视图或主视图,我有一个变量 signedIn 来检查用户是否已登录

const Stack = createStackNavigator<RootStackParamList>();

async function RootNavigator({ signedIn }: { signedIn: boolean | undefined }) {
  if (!signedIn) {
    return (
      <Stack.Navigator screenOptions={{ headerShown: false }}>
        <Stack.Screen name="Auth" component={AuthenticationNavigator} />
        <Stack.Screen
          name="NotFound"
          component={NotFoundScreen}
          options={{ title: "Oops!" }}
        />
      </Stack.Navigator>
    );
  } else {
    return (
      <Stack.Navigator screenOptions={{ headerShown: false }}>
        <Stack.Screen name="Root" component={BottomTabNavigator} />
        <Stack.Screen
          name="NotFound"
          component={NotFoundScreen}
          options={{ title: "Oops!" }}
        />
      </Stack.Navigator>
    );
  }
}

登录变量通过我的主导航函数传递

export default function Navigation({
  colorScheme,
  authStatus
}: {
  colorScheme: ColorSchemeName;
  authStatus: boolean | undefined
}) {
  return (
    <NavigationContainer
      theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
    >
      <RootNavigator signedIn={authStatus} />
    </NavigationContainer>
  );
}

最后 authStatus 变量来自我的主应用程序函数

export default function App() {
  const isLoadingComplete = useCachedResources();
  const colorScheme = useColorScheme();
  const [checkAuth, setCheckAuth] = useState(false);
  const [signedIn, setSignedIn] = useState(false);

  let [fontsLoaded] = useFonts({
    Roboto_100Thin_Italic,
    Roboto_400Regular,
    Roboto_700Bold,
  });

  useEffect(() => {
    async function fetchToken() {
      try {
        const token = await SecureStore.getItemAsync('access_token');

        if (token) {
          setSignedIn(true);
        } else {
          setSignedIn(false);
        }
      } catch (error) {
        console.log(error)
      } finally {
        setCheckAuth(true);
      }
    }

    fetchToken()
  }, [])

  if ((!isLoadingComplete || !fontsLoaded) && !checkAuth) {
    return <AppLoading />;
  } else {
    return (
      <SafeAreaProvider style={{ flex: 1 }}>
        <Provider store={store}>
          <PersistGate persistor={persistor} loading={<AppLoading />}>
            <StatusBar style="auto" />
            <Navigation colorScheme={colorScheme} authStatus={signedIn} />
          </PersistGate>
        </Provider>
      </SafeAreaProvider>
    );
  }
}

我目前在 RootNavigator 中遇到打字稿错误

'RootNavigator' cannot be used as a JSX component.
  Its return type 'Promise<Element>' is not a valid JSX element.

当我执行代码时,我在控制台中收到此错误

Objects are not valid as a React child (found: object with keys {_U, _V, _W, _X}). If you meant to render a collection of children, use an array instead.

0 个答案:

没有答案