React Native 如何等待使用世博路由器,直到准备好

z4iuyo4d  于 2023-11-21  发布在  React
关注(0)|答案(1)|浏览(124)

我的index.js会在用户没有登录的情况下将其路由到欢迎页面,在用户登录的情况下将其路由到主页。但是,由于此路由尝试是在导航器准备就绪之前进行的,因此会导致错误。(从我的测试中最有可能的解释)。我得到的特定错误是在安装根布局组件之前尝试导航。确保根布局组件正在呈现插槽,或其他导航器在第一次渲染。所有其他路由工作。使用Expo SDK 49和路由器v2。下面是my_layout. js和index. js
_layout.js

import { useFonts } from 'expo-font';
import { SplashScreen, Stack } from 'expo-router';
import { useEffect } from 'react';
import { useColorScheme } from 'react-native';

export {
  // Catch any errors thrown by the Layout component.
  ErrorBoundary,
} from 'expo-router';

export const unstable_settings = {
  // Ensure that reloading on `/modal` keeps a back button present.
  initialRouteName: 'index',
};

// Prevent the splash screen from auto-hiding before asset loading is complete.
SplashScreen.preventAutoHideAsync();

export default function RootLayout() {

  const colorScheme = useColorScheme();

  const [loaded, error] = useFonts({
  });

  // Expo Router uses Error Boundaries to catch errors in the navigation tree.
  useEffect(() => {
    if (error) throw error;
  }, [error]);

  useEffect(() => {
    if (loaded) {
      SplashScreen.hideAsync();
    }
  }, [loaded]);

  if (!loaded) {
    return null;
  }
  
  return (
    <Stack screenOptions={{ headerShown: false }}>
      <Stack.Screen name="home" options={{}} />
      <Stack.Screen name="welcome" options={{}} />
    </Stack>
);
}

字符串
index.js

import { Text, View } from 'react-native';
import { Link, router} from 'expo-router';

export default function App(){
    const isLoggedIn = false;

    return (
        <View>
            { isLoggedIn ? router.replace("/home") : router.replace("/welcome") }
            <Text>Sorry, an error has occured, this page should not be visible</Text>
            <Text>Current file: index.js</Text>
            <Link href="/home">Go to default page</Link>
            
        </View>
    )

}


如有任何帮助,将不胜感激!

vtwuwzda

vtwuwzda1#

您可以使用rootNavigationState。将use effect钩子附加到根导航状态键。

import { useRootNavigationState } from 'expo-router'

字符串

const rootNavigationState = useRootNavigationState()
const navigatorReady = rootNavigationState?.key != null

useEffect(() => {
  if (!navigatorReady) return
  // It is ready! Navigate code here!
}, [navigatorReady])

相关问题