RequireAuth.tsx
925 Bytes
import { type ReactNode, useEffect, useState } from 'react';
import { Navigate } from 'react-router-dom';
import { useAuthStore } from '@/store/useAuthStore';
/**
* 路由守卫:未登录跳 /login;本地有 token 但未确认(刷新后从持久化恢复)
* 时调 /api/me 续期校验,校验中先不渲染受保护内容。
*/
export function RequireAuth({ children }: { children: ReactNode }) {
const token = useAuthStore((s) => s.token);
const status = useAuthStore((s) => s.status);
const bootstrap = useAuthStore((s) => s.bootstrap);
const [checked, setChecked] = useState(false);
useEffect(() => {
if (token && status !== 'authed') {
void bootstrap().finally(() => setChecked(true));
} else {
setChecked(true);
}
}, [token, status, bootstrap]);
if (!token) return <Navigate to="/login" replace />;
if (token && !checked) return null;
return <>{children}</>;
}