fix(auth): 优化 ProtectedRoute 加载状态和逻辑

- 使用 PageLoader 替换白色加载背景
- 未登录时不渲染子组件,显示加载状态
- 登录成功后才显示受保护内容

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
zdl
2025-12-25 18:48:33 +08:00
parent 7f7013931d
commit 476f4ad826
2 changed files with 6 additions and 33 deletions

View File

@@ -1,8 +1,8 @@
// src/components/ProtectedRoute.js - 弹窗拦截版本 // src/components/ProtectedRoute.js - 弹窗拦截版本
import React, { useEffect, useRef } from 'react'; import React, { useEffect, useRef } from 'react';
import { Box, VStack, Spinner, Text } from '@chakra-ui/react';
import { useAuth } from '../contexts/AuthContext'; import { useAuth } from '../contexts/AuthContext';
import { useAuthModal } from '../hooks/useAuthModal'; import { useAuthModal } from '../hooks/useAuthModal';
import PageLoader from './Loading/PageLoader';
const ProtectedRoute = ({ children }) => { const ProtectedRoute = ({ children }) => {
const { isAuthenticated, isLoading, user } = useAuth(); const { isAuthenticated, isLoading, user } = useAuth();
@@ -22,26 +22,12 @@ const ProtectedRoute = ({ children }) => {
// 显示加载状态 // 显示加载状态
if (isLoading) { if (isLoading) {
return ( return <PageLoader message="正在验证登录状态..." />;
<Box
height="100vh"
display="flex"
alignItems="center"
justifyContent="center"
bg="gray.50"
>
<VStack spacing={4}>
<Spinner size="xl" color="blue.500" thickness="4px" />
<Text fontSize="lg" color="gray.600">正在验证登录状态...</Text>
</VStack>
</Box>
);
} }
// 未登录时,渲染子组件 + 自动打开弹窗(通过 useEffect // 未登录时,显示加载状态 + 自动弹出认证弹窗(通过 useEffect
// 弹窗会在 useEffect 中自动触发,页面正常显示
if (!isAuthenticated || !user) { if (!isAuthenticated || !user) {
return children; return <PageLoader message="请登录后访问..." />;
} }
// 已登录,渲染子组件 // 已登录,渲染子组件

View File

@@ -2,28 +2,15 @@
// 未登录时跳转到首页,用于三级页面(详情页) // 未登录时跳转到首页,用于三级页面(详情页)
import React from 'react'; import React from 'react';
import { Navigate } from 'react-router-dom'; import { Navigate } from 'react-router-dom';
import { Box, VStack, Spinner, Text } from '@chakra-ui/react';
import { useAuth } from '../contexts/AuthContext'; import { useAuth } from '../contexts/AuthContext';
import PageLoader from './Loading/PageLoader';
const ProtectedRouteRedirect = ({ children }) => { const ProtectedRouteRedirect = ({ children }) => {
const { isAuthenticated, isLoading, user } = useAuth(); const { isAuthenticated, isLoading, user } = useAuth();
// 显示加载状态 // 显示加载状态
if (isLoading) { if (isLoading) {
return ( return <PageLoader message="正在验证登录状态..." />;
<Box
height="100vh"
display="flex"
alignItems="center"
justifyContent="center"
bg="gray.50"
>
<VStack spacing={4}>
<Spinner size="xl" color="blue.500" thickness="4px" />
<Text fontSize="lg" color="gray.600">正在验证登录状态...</Text>
</VStack>
</Box>
);
} }
// 未登录,直接跳转到首页 // 未登录,直接跳转到首页