1e-自动登出
小于 1 分钟
创建一个useEffect,用来处理登录状态
设置定时函数执行 回调函数 取消定时函数
import {useDispatch, useSelector} from "react-redux";
import {useEffect} from "react";
import {logout} from "../store/reducer/authSlice";
const useAutoLogout = () => {
const auth = useSelector(state => state.auth);
const dispatch = useDispatch();
// 创建一个useEffect,用来处理登录状态
useEffect(() => {
const timeout = auth.expirationTime - Date.now();
// 判断timeout的值
if (timeout < 6000) {
dispatch(logout());
return;
}
const timer = setTimeout(() => {
dispatch(logout());
}, timeout);
return () => {
clearTimeout(timer);
};
}, [auth]);
};
export default useAutoLogout;
useAutoLogout
封装成 一个自定义hook const App = () => {
useAutoLogout();
return (
<Layout>
<Routes>
<Route path={"/"} element={<HomePage/>}/>
<Route path={"profile"} element={<NeedAuth><ProfilePage/></NeedAuth>}/>
<Route path={"auth-form"} element={<AuthPage/>}/>
</Routes>
</Layout>
);
};
export default App;