| import React, { useEffect } from "react"; |
| import { Navigate, useLocation } from "react-router-dom"; |
| import { useAuth } from "../features/auth/contexts/AuthContext"; // 更新路径 |
| import { Spin } from "antd"; // 用于加载状态 |
| |
| const ProtectedRoute = ({ children }) => { |
| const { isAuthenticated, loading } = useAuth(); |
| const location = useLocation(); |
| |
| // 可以添加一个调试日志,查看认证状态变化 |
| useEffect(() => { |
| console.log("ProtectedRoute - isAuthenticated:", isAuthenticated); |
| }, [isAuthenticated]); |
| |
| if (loading) { |
| // 当 AuthContext 正在加载认证状态时,显示加载指示器 |
| return ( |
| <div className="flex justify-center items-center min-h-screen"> |
| <Spin size="large" /> |
| </div> |
| ); |
| } |
| |
| if (!isAuthenticated) { |
| // 用户未认证,重定向到登录页,并保存当前位置以便登录后返回 |
| return <Navigate to="/login" state={{ from: location }} replace />; |
| } |
| |
| return children; // 用户已认证,渲染子组件 |
| }; |
| |
| export default ProtectedRoute; |