|
@@ -2,20 +2,24 @@ import React, { useEffect } from 'react';
|
|
|
import { useNavigate } from 'react-router-dom';
|
|
import { useNavigate } from 'react-router-dom';
|
|
|
import { useAuth } from '../hooks/AuthProvider';
|
|
import { useAuth } from '../hooks/AuthProvider';
|
|
|
|
|
|
|
|
|
|
+interface ProtectedRouteProps {
|
|
|
|
|
+ children: React.ReactNode;
|
|
|
|
|
+ redirectTo?: string;
|
|
|
|
|
+}
|
|
|
|
|
|
|
|
-
|
|
|
|
|
-
|
|
|
|
|
-
|
|
|
|
|
-export const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
|
|
|
|
|
|
|
+export const ProtectedRoute = ({
|
|
|
|
|
+ children,
|
|
|
|
|
+ redirectTo = '/login'
|
|
|
|
|
+}: ProtectedRouteProps) => {
|
|
|
const { isAuthenticated, isLoading } = useAuth();
|
|
const { isAuthenticated, isLoading } = useAuth();
|
|
|
const navigate = useNavigate();
|
|
const navigate = useNavigate();
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
useEffect(() => {
|
|
|
// 只有在加载完成且未认证时才重定向
|
|
// 只有在加载完成且未认证时才重定向
|
|
|
if (!isLoading && !isAuthenticated) {
|
|
if (!isLoading && !isAuthenticated) {
|
|
|
- navigate('/login', { replace: true });
|
|
|
|
|
|
|
+ navigate(redirectTo, { replace: true });
|
|
|
}
|
|
}
|
|
|
- }, [isAuthenticated, isLoading, navigate]);
|
|
|
|
|
|
|
+ }, [isAuthenticated, isLoading, navigate, redirectTo]);
|
|
|
|
|
|
|
|
// 显示加载状态,直到认证检查完成
|
|
// 显示加载状态,直到认证检查完成
|
|
|
if (isLoading) {
|
|
if (isLoading) {
|
|
@@ -31,5 +35,5 @@ export const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
|
|
|
return null;
|
|
return null;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- return children;
|
|
|
|
|
|
|
+ return <>{children}</>;
|
|
|
};
|
|
};
|