当前位置:首页 > React

react如何做全局路由拦截

2026-01-25 19:18:37React

在React中实现全局路由拦截通常需要结合路由库(如React Router)和状态管理工具。以下是几种常见方法:

使用React Router的Navigate组件

在React Router v6中,可以通过Navigate组件和useNavigate钩子实现路由拦截。创建一个高阶组件包裹需要保护的路由:

react如何做全局路由拦截

import { Navigate, useLocation } from 'react-router-dom';

const PrivateRoute = ({ children }) => {
  const location = useLocation();
  const isAuthenticated = checkAuth(); // 自定义认证逻辑

  return isAuthenticated 
    ? children 
    : <Navigate to="/login" state={{ from: location }} replace />;
};

// 使用方式
<Route path="/protected" element={<PrivateRoute><ProtectedPage /></PrivateRoute>} />

使用路由守卫组件

创建一个路由守卫组件统一处理所有路由跳转:

import { Routes, Route, useLocation, Navigate } from 'react-router-dom';

const RouterGuard = ({ children }) => {
  const location = useLocation();
  const authRoutes = ['/dashboard', '/profile'];

  if (authRoutes.includes(location.pathname) && !isLoggedIn()) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  return children;
};

// 在根组件中使用
<RouterGuard>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/dashboard" element={<Dashboard />} />
  </Routes>
</RouterGuard>

使用自定义history对象

通过创建自定义history对象实现全局控制:

react如何做全局路由拦截

import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

history.listen((location, action) => {
  if (requiresAuth(location.pathname) && !isAuthenticated()) {
    history.push('/login', { from: location });
  }
});

// 在Router中使用
<Router location={history.location} navigator={history}>
  {/* routes */}
</Router>

结合Context API

对于需要深度集成的场景,可以结合Context管理路由状态:

const AuthContext = createContext();

const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);

  const checkAccess = (path) => {
    if (path.startsWith('/admin') && !user?.isAdmin) {
      return false;
    }
    return true;
  };

  return (
    <AuthContext.Provider value={{ user, checkAccess }}>
      {children}
    </AuthContext.Provider>
  );
};

// 在组件中使用useContext(AuthContext)获取状态

路由配置集中管理

通过集中式路由配置实现统一拦截:

const routes = [
  {
    path: '/',
    element: <Home />,
    public: true
  },
  {
    path: '/admin',
    element: <Admin />,
    middleware: [authMiddleware, adminMiddleware]
  }
];

const renderRoutes = (routes) => (
  <Routes>
    {routes.map((route) => (
      <Route 
        key={route.path}
        path={route.path}
        element={<MiddlewareWrapper route={route} />}
      />
    ))}
  </Routes>
);

每种方法适用于不同场景,简单项目可使用高阶组件方案,复杂项目建议采用集中路由配置或自定义history方案。注意在拦截时保留原始路由状态以便登录后重定向。

标签: 路由全局
分享给朋友:

相关文章

vue  全局刷新实现

vue 全局刷新实现

Vue 全局刷新实现方法 在Vue应用中实现全局刷新通常涉及重新加载整个页面或重置应用状态。以下是几种常见方法: 使用 window.location.reload() 直接调用浏览器原生的刷新方法…

js实现vue路由

js实现vue路由

Vue 路由的基本实现 在 Vue.js 中实现路由功能通常使用 Vue Router 库。Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue R…

vue实现登录路由

vue实现登录路由

Vue 登录路由实现方法 路由配置 在 router/index.js 中配置登录路由和需要权限的路由。使用 meta 字段标记需要认证的路由。 import Vue from 'vue' impo…

vue实现动态路由

vue实现动态路由

动态路由的实现方式 Vue中实现动态路由通常涉及前端和后端的协作,以下是几种常见的实现方式: 基于用户权限的路由控制 在用户登录后,根据其权限动态生成路由表。使用router.addRoutes方…

vue路由守卫怎么实现

vue路由守卫怎么实现

vue路由守卫的实现方法 路由守卫主要用于在导航过程中进行权限控制或数据处理,Vue Router提供了三种主要的路由守卫实现方式: 全局前置守卫 通过router.beforeEach注册全局前置…

vue怎么实现路由缓存

vue怎么实现路由缓存

Vue 实现路由缓存的方法 使用 <keep-alive> 组件 在 Vue 中,可以通过 <keep-alive> 组件实现路由缓存。该组件会缓存不活动的组件实例,避免重复渲…