components_protected_route.tsx 972 B

123456789101112131415161718192021222324252627282930313233343536
  1. import React, { useEffect } from 'react';
  2. import {
  3. useNavigate,
  4. } from 'react-router';
  5. import { useAuth } from './hooks_sys.tsx';
  6. export const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
  7. const { isAuthenticated, isLoading } = useAuth();
  8. const navigate = useNavigate();
  9. useEffect(() => {
  10. // 只有在加载完成且未认证时才重定向
  11. if (!isLoading && !isAuthenticated) {
  12. navigate('/admin/login', { replace: true });
  13. }
  14. }, [isAuthenticated, isLoading, navigate]);
  15. // 显示加载状态,直到认证检查完成
  16. if (isLoading) {
  17. return (
  18. <div className="flex justify-center items-center h-screen">
  19. <div className="loader ease-linear rounded-full border-4 border-t-4 border-gray-200 h-12 w-12"></div>
  20. </div>
  21. );
  22. }
  23. // 如果未认证且不再加载中,不显示任何内容(等待重定向)
  24. if (!isAuthenticated) {
  25. return null;
  26. }
  27. return children;
  28. };