所有模块添加路由守卫
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
import { ReactNode, useEffect, useState } from 'react';
|
||||
import { useLocation, useNavigate } from 'react-router-dom';
|
||||
import { Spin } from 'antd';
|
||||
|
||||
/**
|
||||
* 登录守卫:未登录跳转 /login
|
||||
*
|
||||
* 检查 sessionStorage 中的 userToken,若不存在则跳转登录页。
|
||||
* 登录后会带上 from state,便于登录成功后回跳原页面。
|
||||
*/
|
||||
export default function RequireAuth({ children }: { children: ReactNode }) {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const [checked, setChecked] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const token = sessionStorage.getItem('userToken');
|
||||
if (!token) {
|
||||
// 记录原路径,登录后可回跳
|
||||
navigate('/login', { replace: true, state: { from: location.pathname + location.search } });
|
||||
return;
|
||||
}
|
||||
setChecked(true);
|
||||
}, [navigate, location]);
|
||||
|
||||
if (!checked) {
|
||||
return (
|
||||
<div style={{
|
||||
width: '100vw', height: '100vh',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
background: '#0a1628',
|
||||
}}>
|
||||
<Spin size="large" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
Reference in New Issue
Block a user