当前位置:首页 > React

react router实现路由拦截

2026-01-27 19:17:22React

路由拦截的实现方式

在React Router中实现路由拦截通常涉及以下方法,核心思路是通过高阶组件或自定义路由组件对导航行为进行控制。

使用高阶组件封装路由

通过高阶组件包裹目标路由,在渲染前进行权限或条件校验:

const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => (
  <Route
    {...rest}
    render={(props) =>
      isAuthenticated ? (
        <Component {...props} />
      ) : (
        <Redirect to="/login" />
      )
    }
  />
);

// 使用示例
<PrivateRoute 
  path="/dashboard" 
  component={Dashboard} 
  isAuthenticated={userLoggedIn}
/>

自定义路由组件

创建继承自Route的自定义组件,重写渲染逻辑:

class AuthRoute extends Route {
  render() {
    const { fallbackPath, authCheck, ...props } = this.props;
    return authCheck() 
      ? super.render() 
      : <Redirect to={fallbackPath} />;
  }
}

// 使用示例
<AuthRoute 
  path="/admin" 
  component={AdminPanel}
  authCheck={() => checkAdminRole()}
  fallbackPath="/no-access"
/>

路由守卫模式

在全局路由配置中使用onEnter钩子(v5及之前版本):

<Route 
  path="/profile"
  component={Profile}
  onEnter={(nextState, replace) => {
    if (!hasToken()) replace('/auth');
  }}
/>

使用useNavigate拦截

React Router v6+推荐方案,通过自定义导航钩子:

const useAuthRedirect = () => {
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    const publicPaths = ['/login', '/register'];
    if (!publicPaths.includes(location.pathname) && !isAuth()) {
      navigate('/login', { state: { from: location } });
    }
  }, [location]);
};

// 在根组件调用
function App() {
  useAuthRedirect();
  return <Routes>...</Routes>;
}

动态路由加载拦截

结合React.lazy实现异步路由拦截:

const LazyAdmin = React.lazy(() => {
  return verifyAdmin().then(
    () => import('./Admin'),
    () => ({ default: () => <Redirect to="/" /> })
  );
});

<Route path="/admin" element={
  <Suspense fallback={<Spinner />}>
    <LazyAdmin />
  </Suspense>
} />

路由配置集中管理

通过声明式配置实现集中式路由守卫:

react router实现路由拦截

const routeConfig = [
  {
    path: '/',
    element: <Home />,
    guards: [checkGuest],
  },
  {
    path: '/settings',
    element: <Settings />,
    guards: [checkAuth, checkSubscription],
    redirect: '/upgrade',
  }
];

const GuardedRoutes = () => {
  return (
    <Routes>
      {routeConfig.map((route) => (
        <Route 
          key={route.path}
          path={route.path}
          element={<RouteGuard {...route} />}
        />
      ))}
    </Routes>
  );
};

每种方案适用于不同场景,v6+推荐使用组合式导航钩子方案,v4/v5可采用高阶组件模式。实际选择应考虑项目架构版本和技术栈的统一性。

标签: 路由react
分享给朋友:

相关文章

react架构如何

react架构如何

React 架构核心概念 React 的架构围绕组件化、虚拟 DOM 和单向数据流设计。组件是构建用户界面的独立模块,分为函数组件和类组件。虚拟 DOM 通过高效的 Diff 算法减少直接操作真实 D…

react 如何遍历

react 如何遍历

遍历数组 在React中遍历数组通常使用map方法,它会返回一个新的数组。map是处理数组并渲染列表元素的首选方法。 const items = ['Apple', 'Banana', 'Cherr…

react如何重启

react如何重启

重启 React 应用的方法 重新加载当前页面 使用 window.location.reload() 强制刷新页面,这会重新加载整个应用并重置所有状态。 window.location…

react如何折叠

react如何折叠

在 React 中实现折叠功能 使用 useState 管理折叠状态 通过 useState 定义一个状态变量来控制折叠面板的显示与隐藏。例如: const [isCollapsed, setIsC…

react如何减少setState

react如何减少setState

减少 React 中 setState 调用的方法 合并多次状态更新 使用函数式更新方式合并多次 setState 调用。React 会将多次状态更新批量处理,避免不必要的重新渲染。 // 非函…

小白如何搭建react

小白如何搭建react

安装 Node.js 和 npm 确保系统已安装 Node.js(包含 npm)。可通过官网下载安装包(https://nodejs.org/),选择 LTS 版本。安装完成后,终端运行以下命令验证版…