ProtectedRoute.tsx 1.2 KB

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