当前位置:首页 > React

react实现beforeEach

2026-01-26 14:17:11React

React 实现类似路由守卫的 beforeEach 功能

在 React 中实现类似 Vue 路由守卫的 beforeEach 功能,可以通过 React Router 提供的导航守卫机制结合自定义逻辑完成。

使用 React Router v6 的导航守卫

React Router v6 提供了 useNavigateuseLocation 钩子,结合 useEffect 可以实现路由跳转前的拦截逻辑。

react实现beforeEach

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

function RouterGuard({ children }) {
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    // 在这里添加路由跳转前的逻辑
    const isAuthenticated = checkAuth(); // 自定义认证检查
    if (!isAuthenticated && location.pathname !== '/login') {
      navigate('/login', { replace: true });
    }
  }, [location, navigate]);

  return children;
}

自定义高阶组件封装

可以创建一个高阶组件来封装路由守卫逻辑,使代码更易于复用。

react实现beforeEach

function withRouterGuard(WrappedComponent, guardFn) {
  return function(props) {
    const navigate = useNavigate();
    const location = useLocation();

    useEffect(() => {
      guardFn({ navigate, location });
    }, [location, navigate]);

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

在路由配置中应用守卫

可以在路由配置中为需要保护的路由添加守卫组件。

const routes = [
  {
    path: '/',
    element: (
      <RouterGuard>
        <HomePage />
      </RouterGuard>
    ),
  },
  {
    path: '/dashboard',
    element: (
      <RouterGuard>
        <Dashboard />
      </RouterGuard>
    ),
  },
];

实现完整的认证流程示例

function App() {
  return (
    <Routes>
      <Route path="/login" element={<Login />} />
      <Route
        path="/protected"
        element={
          <RequireAuth>
            <ProtectedPage />
          </RequireAuth>
        }
      />
    </Routes>
  );
}

function RequireAuth({ children }) {
  const auth = useAuth();
  const location = useLocation();

  if (!auth.user) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  return children;
}

处理异步验证逻辑

对于需要异步验证的场景,可以使用 Promise 或 async/await。

useEffect(() => {
  const checkAccess = async () => {
    const hasAccess = await verifyUserAccess();
    if (!hasAccess) {
      navigate('/no-access');
    }
  };
  checkAccess();
}, [location, navigate]);

这些方法提供了在 React 中实现路由跳转前逻辑的各种方式,可以根据具体需求选择最适合的实现方案。

标签: reactbeforeEach
分享给朋友:

相关文章

如何react页面

如何react页面

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

react native 如何

react native 如何

React Native 开发基础 React Native 是一个用于构建跨平台移动应用的框架,允许开发者使用 JavaScript 和 React 编写代码,同时生成原生 iOS 和 Androi…

react 如何执行

react 如何执行

安装 Node.js 和 npm React 开发需要 Node.js 环境,因为它提供了 npm(或 yarn)包管理工具。从 Node.js 官网 下载并安装最新 LTS 版本。安装完成后,在终端…

如何生成react代码

如何生成react代码

使用 Create React App 生成项目 安装 Node.js 后,通过命令行工具运行以下命令创建新项目: npx create-react-app my-app cd my-app np…

react如何开发组件

react如何开发组件

React 组件开发基础 React 组件分为函数组件和类组件两种形式。函数组件是现代 React 开发的主流方式,结合 Hooks 可以实现完整功能。 函数组件示例: function Gree…

react性能如何

react性能如何

React 性能特点 React 通过虚拟 DOM(Virtual DOM)和高效的 diff 算法优化性能。虚拟 DOM 减少了直接操作真实 DOM 的开销,仅在必要时更新变化的部分。React 的…