Browse Source

fix: useProtectedRoute延迟导航执行直到根布局挂载完成

zengkunsen 4 months ago
parent
commit
d543ad9934
2 changed files with 13 additions and 6 deletions
  1. 2 1
      app/_layout.tsx
  2. 11 5
      context/AuthProvider.tsx

+ 2 - 1
app/_layout.tsx

@@ -1,4 +1,3 @@
-import "./global.css"
 import { Stack } from 'expo-router/stack';
 import AuthProvider, { useAuth } from '../context/AuthProvider';
 import { EXPO_PUBLIC_NODE_ENV } from '@env';
@@ -10,6 +9,8 @@ import { usePushNotifications } from './hooks/usePushNotifications';
 import Constants from 'expo-constants';
 import { Alert, AppState } from 'react-native';
 import * as Updates from 'expo-updates';
+import "./global.css"
+
 export default function RootLayout() {
     const [isLoading, setIsLoading] = useState(true);
     const { user } = useAuth();

+ 11 - 5
context/AuthProvider.tsx

@@ -18,25 +18,31 @@ type AuthProvider = {
 
 function useProtectedRoute(user: User | null) {
     const segments = useSegments();
+    // 添加状态跟踪根布局是否已挂载
+    const [isLayoutMounted, setIsLayoutMounted] = useState(false);
 
     const isUserEmpty = (user: User | null): boolean => {
         return !user || Object.values(user).every((value) => value === undefined);
     };
 
     useEffect(() => {
-        if (!segments.length) return;
-        // console.log('Current segment:', segments[0]);
-        // console.log('Is user empty?', isUserEmpty(user));
+        // 标记根布局已挂载
+        setIsLayoutMounted(true);
+    }, []);
+
+    useEffect(() => {
+        // 等待根布局挂载完成且路由段准备好
+        if (!isLayoutMounted || !segments.length) return;
+
         const inAuthGroup = segments[0] === '(auth)';
         const inPublicGroup = segments[0] === '(public)';
-        // console.log('In auth group?', inAuthGroup);
 
         if (isUserEmpty(user) && !inPublicGroup) {
             router.replace('/login');
         } else if (!isUserEmpty(user) && inPublicGroup) {
             router.replace('/(auth)/(tabs)/(home)/mainPage');
         }
-    }, [user, segments]);
+    }, [user, segments, isLayoutMounted]); // 添加 isLayoutMounted 依赖
 }
 
 export const AuthContext = createContext<AuthProvider>({