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

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

相关文章

js实现vue路由

js实现vue路由

Vue路由基础实现 使用Vue Router实现前端路由需要先安装并配置路由库。Vue Router是Vue.js官方的路由管理器。 安装Vue Router: npm install vue-r…

vue实现路由历史

vue实现路由历史

Vue 实现路由历史管理 在 Vue 中,路由历史管理通常通过 Vue Router 实现。Vue Router 提供了两种历史记录模式:hash 模式和 history 模式。以下是具体实现方法。…

vue实现动态路由按钮

vue实现动态路由按钮

Vue 实现动态路由按钮的方法 动态路由按钮的实现通常涉及权限控制,根据用户角色或权限动态显示或隐藏路由按钮。以下是几种常见方法: 基于路由元信息(meta)和v-if控制 在路由配置中添加权限标…

vue路由实现内部切换

vue路由实现内部切换

Vue路由实现内部切换的方法 Vue Router是Vue.js官方的路由管理器,用于构建单页面应用(SPA)。以下是几种常见的路由切换方式: 使用<router-link>组件…

vue实现点击跳转路由

vue实现点击跳转路由

vue实现点击跳转路由的方法 在Vue中实现点击跳转路由,可以通过以下几种方式完成,具体取决于项目使用的路由管理工具(如Vue Router)以及需求场景。 使用router-link组件 rout…

vue实现路由

vue实现路由

Vue 路由的实现方法 Vue 中实现路由通常使用 Vue Router 库。以下是具体的实现步骤: 安装 Vue Router 在项目中通过 npm 或 yarn 安装 Vue Router:…