// src/components/ProtectedRoute.js - Session版本 import React from 'react'; import { Navigate } from 'react-router-dom'; import { Box, VStack, Spinner, Text } from '@chakra-ui/react'; import { useAuth } from '../contexts/AuthContext'; const ProtectedRoute = ({ children }) => { const { isAuthenticated, isLoading, user } = useAuth(); // 显示加载状态 if (isLoading) { return ( 正在验证登录状态... ); } // 记录当前路径,登录后可以回到这里 let currentPath = window.location.pathname + window.location.search; let redirectUrl = `/auth/signin?redirect=${encodeURIComponent(currentPath)}`; // 检查是否已登录 if (!isAuthenticated || !user) { return ; } // 已登录,渲染子组件 // return children; // 更新逻辑 如果 currentPath 是首页 登陆成功后跳转到个人中心 if (currentPath === '/' || currentPath === '/home') { currentPath = '/profile'; redirectUrl = `/auth/signin?redirect=${encodeURIComponent(currentPath)}`; return ; } else { // 否则正常渲染 return children; } }; export default ProtectedRoute;