当前位置:首页 > 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>
} />

路由配置集中管理

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

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 router实现路由拦截

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

相关文章

如何学习react

如何学习react

学习 React 的步骤 理解基础概念 React 是一个用于构建用户界面的 JavaScript 库。学习 React 之前,建议掌握 JavaScript 的基础知识,包括 ES6+ 语法(如箭头…

如何react页面

如何react页面

创建 React 页面 使用 create-react-app 快速初始化项目: npx create-react-app my-app cd my-app npm start 编写组件代码 在 s…

vue 路由实现

vue 路由实现

Vue 路由实现方法 Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。以下是实现 Vue 路由的基本步骤: 安装 Vue Router 使用 npm 或 y…

react如何取消渲染

react如何取消渲染

取消渲染的方法 在React中,取消渲染通常指的是在某些条件下阻止组件渲染或中断正在进行的渲染过程。以下是几种常见的方法: 条件渲染 通过条件判断决定是否渲染组件或部分内容。可以使用if语句或三元运…

react moment如何使用

react moment如何使用

安装 react-moment 通过 npm 或 yarn 安装 react-moment: npm install react-moment 或 yarn add react-moment 基本…

如何优化react

如何优化react

优化 React 性能的方法 使用 React.memo 或 PureComponent 对于函数组件,使用 React.memo 进行记忆化,避免不必要的重新渲染。类组件可以使用 PureCompo…