当前位置:首页 > 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方案。注意在拦截时保留原始路由状态以便登录后重定向。

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

相关文章

php 路由实现的

php 路由实现的

PHP 路由实现方法 基于原生 PHP 实现路由 创建一个简单的路由解析器,通过解析 URL 路径来调用对应的控制器或函数。 // 定义路由表 $routes = [ '/' => '…

elementui路由

elementui路由

使用Element UI与Vue Router集成 Element UI是一个基于Vue.js的组件库,与Vue Router可以无缝集成。通过Vue Router管理路由,结合Element UI的…

vue实现tab路由

vue实现tab路由

Vue 实现 Tab 路由的方法 在 Vue 中实现 Tab 路由通常需要结合 Vue Router 和动态组件或条件渲染。以下是几种常见方法: 使用 Vue Router 动态路由 配置路由文件…

vue 实现路由弹窗

vue 实现路由弹窗

实现路由弹窗的基本思路 在Vue中实现路由弹窗的核心是利用路由参数或查询参数控制弹窗的显示,同时保持页面URL与弹窗状态的同步。常见方法包括动态路由、嵌套路由或通过<router-view>…

vue实现路由切换

vue实现路由切换

Vue 路由切换实现方法 安装 Vue Router 通过 npm 或 yarn 安装 Vue Router 依赖包: npm install vue-router 配置路由 在项目中创建路由配置文…

vue实现路由原理

vue实现路由原理

Vue 路由实现原理 Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。其核心原理基于前端路由技术,通过监听 URL 变化并动态渲染组件。 路由模式 Vue R…