ProtectedRoute.tsx 1.0 KB

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