React中怎么实现类似Vue中的路由守卫功能?

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

阅读 1.6k
2 个回答
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 (
    <Router>
      <Switch>
        <Route path="/login">
          <LoginPage />
        </EventPage>
        <Route path="/dashboard">
          <DashboardPage />
        </Route>
        <Route path="/profile">
          <ProfilePage />
        </Route>
        <Route path="/">
          <HomePage />
        </Route>
      </Switch>
    </Router>
  );
};
  1. 接口级别权限校验,用户未登录,直接返回302重定向到登录页面
  2. 页面级别权限校验, react 可以监控useinfo里面的相关信息

     const [state] = useGlobaStore('useInfo')
    
     return state.usename ? <>welcome</> : <unLogged/>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题