diff --git a/components/providers/AuthGuard.tsx b/components/providers/AuthGuard.tsx index 34d7fa9..61deabc 100644 --- a/components/providers/AuthGuard.tsx +++ b/components/providers/AuthGuard.tsx @@ -7,16 +7,17 @@ import { useCurrentUser } from '@/lib/hooks/useAuth'; export function AuthGuard({ children }: { children: React.ReactNode }) { const router = useRouter(); - const { isAuthenticated, isLoading } = useAuthStore(); + const { isAuthenticated, isHydrated } = useAuthStore(); const { isLoading: isUserLoading } = useCurrentUser(); useEffect(() => { - if (!isLoading && !isUserLoading && !isAuthenticated) { + if (isHydrated && !isUserLoading && !isAuthenticated) { + console.log('[AuthGuard] Redirecting to login - user not authenticated'); router.push('/login'); } - }, [isAuthenticated, isLoading, isUserLoading, router]); + }, [isAuthenticated, isHydrated, isUserLoading, router]); - if (isLoading || isUserLoading) { + if (!isHydrated || isUserLoading) { return (
diff --git a/stores/authStore.ts b/stores/authStore.ts index 056b599..edf27d8 100644 --- a/stores/authStore.ts +++ b/stores/authStore.ts @@ -57,9 +57,11 @@ export const useAuthStore = create()( } state.isHydrated = true; + state.isLoading = false; // 水合完成后停止 loading console.log('[AuthStore] Hydration completed', { userId: state.user?.id, - isAuthenticated: state.isAuthenticated + isAuthenticated: state.isAuthenticated, + isLoading: state.isLoading }); } },