feat(auth): 实现登录注册功能并重构 App 组件
- 新增登录和注册页面组件
- 实现用户认证和权限管理逻辑
- 重构 App 组件,使用 Router 和 AuthProvider
- 添加管理员面板和论坛页面组件
Change-Id: Iaa4502616970e75e3268537f73c75dac8f60e24d
diff --git a/src/routes/ProtectedRoute.jsx b/src/routes/ProtectedRoute.jsx
index ea53b10..4caa16c 100644
--- a/src/routes/ProtectedRoute.jsx
+++ b/src/routes/ProtectedRoute.jsx
@@ -1,35 +1,32 @@
-import { Navigate } from 'react-router-dom';
-import { useEffect, useState } from 'react';
-import { Spin } from 'antd';
+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 [loading, setLoading] = useState(true);
- const [isAuthenticated, setIsAuthenticated] = useState(false);
+ const { isAuthenticated, loading } = useAuth();
+ const location = useLocation();
+ // 可以添加一个调试日志,查看认证状态变化
useEffect(() => {
- // 简单检查是否有token
- const token = localStorage.getItem('token');
- if (token) {
- setIsAuthenticated(true);
- }
- setLoading(false);
- }, []);
+ console.log("ProtectedRoute - isAuthenticated:", isAuthenticated);
+ }, [isAuthenticated]);
if (loading) {
+ // 当 AuthContext 正在加载认证状态时,显示加载指示器
return (
- <div className="flex justify-center items-center h-screen">
- <Spin spinning={loading} fullScreen tip="加载中...">
- {children}
- </Spin>
+ <div className="flex justify-center items-center min-h-screen">
+ <Spin size="large" />
</div>
);
}
if (!isAuthenticated) {
- return <Navigate to="/login" replace />;
+ // 用户未认证,重定向到登录页,并保存当前位置以便登录后返回
+ return <Navigate to="/login" state={{ from: location }} replace />;
}
- return children;
+ return children; // 用户已认证,渲染子组件
};
-export default ProtectedRoute;
\ No newline at end of file
+export default ProtectedRoute;