当前位置:首页 > React

react实现全局路由守卫

2026-01-27 17:57:39React

全局路由守卫的实现方法

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

使用React Router的Navigate组件

通过包装路由组件并在渲染前进行权限检查:

react实现全局路由守卫

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

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

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

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

使用React Router v6的loader函数

在数据加载阶段进行拦截:

const router = createBrowserRouter([
  {
    path: '/',
    element: <Root />,
    loader: () => {
      if (!isLoggedIn()) {
        throw redirect('/login');
      }
      return null;
    }
  }
]);

自定义高阶组件(HOC)

创建可重用的路由守卫组件:

react实现全局路由守卫

function withRouterGuard(WrappedComponent, checkFn) {
  return (props) => {
    const navigate = useNavigate();
    useEffect(() => {
      if (!checkFn()) {
        navigate('/fallback');
      }
    }, [navigate]);

    return <WrappedComponent {...props} />;
  };
}

使用上下文和自定义钩子

结合Context API实现全局状态管理:

const AuthContext = createContext();

const useAuth = () => {
  const { pathname } = useLocation();
  const { user } = useContext(AuthContext);

  useEffect(() => {
    if (!user && !['/login', '/register'].includes(pathname)) {
      window.location.href = '/login';
    }
  }, [pathname, user]);
};

路由配置集中管理

通过统一的路由配置文件实现守卫:

const routes = [
  {
    path: '/admin',
    component: AdminPage,
    guards: [authGuard, roleGuard('admin')]
  }
];

const resolvedRoutes = routes.map(route => ({
  ...route,
  element: route.guards.reduce(
    (acc, guard) => guard(acc),
    <route.component />
  )
}));

注意事项

  • 守卫逻辑应避免阻塞渲染过程
  • 需要处理路由跳转时的状态保存
  • 对于异步验证(如JWT校验)需添加加载状态
  • 服务端渲染场景需考虑SSR兼容性

以上方法可根据具体需求组合使用,React Router v6推荐使用loader方案或Navigate组件实现路由守卫。

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

相关文章

Vue实现路由监

Vue实现路由监

Vue实现路由监听的方法 在Vue中,可以通过多种方式监听路由变化,以下是常见的实现方法: 使用Vue Router的全局前置守卫 router.beforeEach((to, from, nex…

vue实现前端路由

vue实现前端路由

Vue 前端路由实现方法 Vue 前端路由可以通过 vue-router 库实现,这是 Vue 官方推荐的路由解决方案。 安装 vue-router 通过 npm 或 yarn 安装 vue-rou…

react如何获取路由

react如何获取路由

获取当前路由路径 在React中获取当前路由路径可以通过react-router-dom提供的useLocation钩子。useLocation返回一个包含当前路由信息的对象,其中pathname属性…

elementui路由

elementui路由

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

vue路由实现机制

vue路由实现机制

Vue 路由实现机制 Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。其核心机制包括路由匹配、导航守卫、动态路由等。 路由匹配 Vue Router 通过路由…

vue路由如何实现

vue路由如何实现

vue路由的实现方法 Vue路由可以通过Vue Router库来实现。Vue Router是Vue.js官方的路由管理器,用于构建单页面应用(SPA)。 安装Vue Router 使用npm或yar…