React中怎么实现类似Vue中的路由守卫功能?-灵析社区

WhatUpDanger

有没有react hooks处理方法?可以直接监听到路由跳转的变化,然后进行判断处理?比如用户如果未登录访问某个页面,跳转到登录页。

阅读量:169

点赞量:0

问AI
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 ( ); };