从React Router useLocation挂钩中排除路径?

时间:2020-03-02 20:07:51

标签: javascript reactjs react-router

我正在使用React Router的useLocation钩子来标记活动标签,就像这样:

import React from "react";
import { Link, useLocation } from "react-router-dom";
import Tabs from "@material-ui/core/Tabs";
import Tab from "@material-ui/core/Tab";
import Routes from "../../../routes";

const Links = () => {

  let location = useLocation();

  return (
      <Tabs value={location.pathname}>
        {Routes.map((route, key) => {
          return (
            <Tab
              component={Link}
              to={route.path}
              label={route.label}
              key={key}
              value={route.path}
            />
          );
        })}
      </Tabs>
  );
}

还有一个示例Routes

import { Foo } from "../pages";

    const Routes = [
      {
        path: "/foo",
        label: "Foo",
        component: Foo
      }
    ]

上面的方法工作得很好,直到我没有决定添加带有辅助导航的边栏。为了区分主导航和辅助导航,我修改了Routes

import { Foo, Bar } from "../pages";

const Routes = [
  {
    path: "/foo",
    label: "Foo",
    tabs: true,
    component: Foo
  },
  {
    path: "/foo/bar",
    label: "Bar",
    side: true,
    component: Bar
  },
]

最初,标签还显示了其他导航,但是使用filtermap很容易克服:

...snip
<Tabs value={location.pathname}>
        {Routes.filter(r => r.tab === true).map((item, key) => {
          return (
...snip

但是边栏链接仍通过<Tabs>传递到value={location.pathname}组件。如何在将剩余的分配给/的{​​{1}}属性之前,从location.pathname过滤/删除所有路径超过<Tabs>的路径?

需要明确的是,我只想传递以下内容:

value

而不是:

/foo
/bar
/baz

编辑: 我现在正在使用的笨拙解决方案是:

/foo/bar
/bar/foo/foo

0 个答案:

没有答案