22301014 | b1477f7 | 2025-06-07 22:54:40 +0800 | [diff] [blame^] | 1 | import React, { useEffect } from 'react'; |
| 2 | import { useAppSelector, useAppDispatch } from '../store/hooks'; // 导入 hooks |
| 3 | import { useNavigate } from 'react-router'; |
| 4 | import { refreshToken } from '../feature/auth/authSlice'; // 导入刷新 token 的 thunk |
| 5 | |
| 6 | interface ProtectedRouteProps { |
| 7 | children: React.ReactNode; |
| 8 | } |
| 9 | |
| 10 | const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ children }) => { |
| 11 | const { isAuth, token } = useAppSelector((state) => state.auth); |
| 12 | const navigate = useNavigate(); |
| 13 | const dispatch = useAppDispatch(); |
| 14 | |
| 15 | useEffect(() => { |
| 16 | const tryRefreshToken = async () => { |
| 17 | if (!token) { |
| 18 | navigate('/login'); // 如果没有 token,跳转到登录页 |
| 19 | } |
| 20 | if (!isAuth && token) { |
| 21 | try { |
| 22 | await dispatch(refreshToken(token)).unwrap(); // 尝试刷新 token |
| 23 | } catch { |
| 24 | navigate('/login'); |
| 25 | } |
| 26 | } |
| 27 | }; |
| 28 | |
| 29 | tryRefreshToken(); // 执行 token 刷新 |
| 30 | }, [isAuth, token, dispatch, navigate]); |
| 31 | |
| 32 | // 如果已认证则渲染 children,否则返回 null |
| 33 | return isAuth ? <>{children}</> : null; |
| 34 | }; |
| 35 | |
| 36 | export default ProtectedRoute; |