import React, { useEffect } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
// 检查用户是否登录
const useAuth = () => {
const getUser = () => {
// 从localStorage, sessionStorage, 或者 redux store 等获取用户登录信息
return localStorage.getItem('user');
}
return {
isLogged: !!getUser(),
};
};
const useRouteGuard = () => {
const history = useHistory();
const location = useLocation();
const { isLogged } = useAuth();
useEffect(() => {
const onRouteChange = () => {
if (!isLogged && location.pathname !== '/login') {
history.push('/login');
}
};
onRouteChange();
// 加location.pathname依赖
}, [history, location.pathname, isLogged]);
};
// 在你的组件里用这个Hook
const App = () => {
useRouteGuard(); // 启用路由守卫
return (
);
};