ProtectedRoute.tsx 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import React, { useEffect } from 'react';
  2. import {
  3. useNavigate,
  4. useLocation,
  5. } from 'react-router';
  6. import { useAuth } from '../hooks/AuthProvider';
  7. export const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
  8. const { isAuthenticated, isLoading } = useAuth();
  9. const navigate = useNavigate();
  10. const location = useLocation();
  11. useEffect(() => {
  12. // 只有在加载完成且未认证时才重定向
  13. if (!isLoading && !isAuthenticated) {
  14. // 保存当前路径到localStorage,用于登录后跳转回来源页
  15. const returnUrl = location.pathname + location.search;
  16. localStorage.setItem('mobile_return_url', returnUrl);
  17. navigate('/mobile/login', { replace: true });
  18. }
  19. }, [isAuthenticated, isLoading, navigate, location]);
  20. // 显示加载状态,直到认证检查完成
  21. if (isLoading) {
  22. return (
  23. <div className="flex justify-center items-center h-screen">
  24. <div className="loader ease-linear rounded-full border-4 border-t-4 border-gray-200 h-12 w-12"></div>
  25. </div>
  26. );
  27. }
  28. // 如果未认证且不再加载中,不显示任何内容(等待重定向)
  29. if (!isAuthenticated) {
  30. return null;
  31. }
  32. return children;
  33. };