」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 使用 React Router v6 在 React 中實作麵包屑

使用 React Router v6 在 React 中實作麵包屑

發佈於2024-11-06
瀏覽:131

Implementing Breadcrumbs in React using React Router v6

面包屑在网页开发中非常重要,因为它们为用户提供了一种方法来跟踪他们在我们网页中的当前位置,并帮助我们的网页导航。

在本指南中,我们将使用 React-router v6 和 Bootstrap 在 React 中实现面包屑。

React-router v6 是 React 和 React Native 中使用的路由库,用于在网页或 Web 应用程序中导航。

我们的实现使用 Typescript,但它也可以轻松用于基于 Javascript 的项目。

设置

首先,如果尚未安装的话,让我们在项目中安装react-router-dom:

npm 安装react-router-dom

或者替代方案,使用纱线:

纱线添加react-router-dom

让我们还安装 bootstrap 来设计我们的组件:

npm 安装引导程序

实现我们的组件

然后,我们创建一个 Breadcrumbs.tsx 组件,它将包含面包屑的标记,还包括确定相对于根位置的当前位置所需的逻辑。

让我们首先为组件添加一个简单的标记:

 

该组件当前只有一个后退按钮。让我们为后退按钮添加一个简单的实现,这样当单击时,应该加载上一页:

  const goBack = () => {
    window.history.back();
  };

下一步将编写一个函数,该函数将使用 matchRoutes 函数来获取当前路由并应用转换来过滤出与当前路由相关的所有路由。
matchRoute 接受 AgnosticRouteObject 类型的对象数组并返回 AgnosticRouteMatch[] | null,其中 T 是我们传入的对象的类型。
另外需要注意的是,该对象必须包含名为 path.

的属性

我们首先为我们的路由声明一个接口:

export interface IRoute {
  name: string;
  path: string; //Important
}

然后让我们声明我们的路线:

const routes: IRoute[] = [
  {
    path: '/home',
    name: 'Home'
  },
  {
    path: '/home/about',
    name: 'About'
  },
  {
    path: '/users',
    name: 'Users'
  },
  {
    path: '/users/:id',
    name: 'User'
  },
  {
    path: '/users/:id/settings/edit',
    name: 'Edit User Settings'
  }
];

我们还声明了一个变量来保存 useLocation 钩子,还声明了另一个变量来保存面包屑的状态:

const location = useLocation();
const [crumbs, setCrumbs] = useState([]);

接下来我们来实现我们的功能:

const getPaths = () => {
  const allRoutes = matchRoutes(routes, location);
  const matchedRoute = allRoutes ? allRoutes[0] : null;
  let breadcrumbs: IRoute[] = [];
  if (matchedRoute) {
    breadcrumbs = routes
      .filter((x) => matchedRoute.route.path.includes(x.path))
      .map(({ path, ...rest }) => ({
        path: Object.keys(matchedRoute.params).length
          ? Object.keys(matchedRoute.params).reduce(
              (path, param) => path.replace(`:${param}`, matchedRoute.params[param] as string), path)
          : path,
        ...rest,
      }));
  }
  setCrumbs(breadcrumbs);
};

这里,我们首先获取与当前位置匹配的所有路线:
const allRoutes = matchRoutes(路线, 位置);

然后我们快速检查是否返回任何结果,并选择第一个:
常量匹配路由=所有路由? allRoutes[0] : null;

接下来,我们过滤掉所有与当前路由匹配的路由:
路线.过滤器((x)=>matchedRoute.route.path.includes(x.path))

然后让我们使用结果创建一个新数组,检查路径是否有参数,然后用参数值交换动态路由:

 .map(({ path, ...rest }) => ({
          path: Object.keys(matchedRoute.params).length
            ? Object.keys(matchedRoute.params).reduce(
                (path, param) => path.replace(`:${param}`, matchedRoute.params[param] as string),
                path
              )
            : path,
          ...rest,
        }));

这确保了如果我们在路由中将路由声明为 /users/:id/edit 并将 id 传递为 1,那么我们将得到 /users/1/edit。

接下来,让我们在 useEffect 中调用我们的函数,以便它在每次位置更改时运行:

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

完成此操作后,我们可以在标记中使用面包屑:

{crumbs.map((x: IRoute, key: number) =>
  crumbs.length === key   1 ? (
    
  • {x.name}
  • ) : (
  • {x.name}
  • ) )}

    此处,显示除最后一个仅显示名称之外的所有面包屑及其链接。

    这样,我们现在就有了完整的 BreadCrumbs.tsx 组件:

    import { useEffect, useState } from 'react';
    import { Link, matchRoutes, useLocation } from 'react-router-dom';
    
    export interface IRoute {
      name: string;
      path: string;
    }
    
    const routes: IRoute[] = [
      {
        path: '/home',
        name: 'Home',
      },
      {
        path: '/home/about',
        name: 'About',
      },
      {
        path: '/users',
        name: 'Users',
      },
      {
        path: '/users/:id/edit',
        name: 'Edit Users by Id',
      },
    ];
    
    const Breadcrumbs = () => {
      const location = useLocation();
      const [crumbs, setCrumbs] = useState([]);
    
      //   const routes = [{ path: '/members/:id' }];
    
      const getPaths = () => {
        const allRoutes = matchRoutes(routes, location);
        const matchedRoute = allRoutes ? allRoutes[0] : null;
        let breadcrumbs: IRoute[] = [];
        if (matchedRoute) {
          breadcrumbs = routes
            .filter((x) => matchedRoute.route.path.includes(x.path))
            .map(({ path, ...rest }) => ({
              path: Object.keys(matchedRoute.params).length
                ? Object.keys(matchedRoute.params).reduce(
                    (path, param) => path.replace(`:${param}`, matchedRoute.params[param] as string),
                    path
                  )
                : path,
              ...rest,
            }));
        }
        setCrumbs(breadcrumbs);
      };
    
      useEffect(() => {
        getPaths();
      }, [location]);
    
      const goBack = () => {
        window.history.back();
      };
    
      return (
        
    ); }; export default Breadcrumbs;

    然后我们可以在应用程序的任何部分使用该组件,最好是在布局中。

    结论

    我们已经了解了如何实现一个简单的面包屑组件,我们可以将其添加到我们的应用程序中以改进导航和用户体验。

    有用的链接

    https://stackoverflow.com/questions/66265608/react-router-v6-get-path-pattern-for-current-route

    https://medium.com/@mattywilliams/generating-an-automatic-breadcrumb-in-react-router-fed01af1fc3,这篇文章的灵感来自于此。

    版本聲明 本文轉載於:https://dev.to/bayo99/implementing-breadcrumbs-in-react-using-react-router-v6-363o?1如有侵犯,請聯絡[email protected]刪除
    最新教學 更多>

    免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

    Copyright© 2022 湘ICP备2022001581号-3