首页 > 解决方案 > 无法使用 react-router-dom 5.2.0 编写嵌套路由?

问题描述

我正在尝试使用 react-router-dom 5.2.0 在 React 中访问具有嵌套路由的子组件。在这里您可以找到项目的 CodeSandbox 链接:https ://codesandbox.io/s/nested-routes-8c7wq?file=/src/App.js

首先,让我向您展示我的页面的树结构。

主页(主页、关于、组织)的路由位于 src/routes 文件夹中。所以他们的链接看起来像:

在这一点上,一切对我来说都很好。问题出在嵌套部分..

在组织页面上,我必须能够在 MainContent 和 SecondContent 之间切换。因此,该页面的链接必须如下所示:

但我无法打印任何这些内容......

标签: javascriptreactjsreact-router-domreact-domnested-routes

解决方案


如果你想构建嵌套路径,你应该使用当前路由匹配中的 andpathurl从那里构建嵌套路由和链接。

src/pages/组织

import { Switch, Route, useRouteMatch } from "react-router-dom";

const Organizations = (props) => {
  const { path, url } = useRouteMatch(); // <-- get current path and url
  const [value, setValue] = useState("");

  const menuLinks = {
    data: [
      {
        id: 0, // <-- fix React key issue in NavBar
        title: "StackOverflow",
        to: `${url}/maincontent` // <-- build nested link
      },
      {
        id: 1, // <-- fix React key issue in NavBar
        title: "BitBucket",
        to: `${url}/secondcontent` // <-- build nested link
      }
    ]
  };

  return (
    <div>
      <NavBar changeValue={(value) => setValue(value)} menuLinks={menuLinks} />
      <div>
        <Switch>
          <Route
            render={() => <MainContent title={value} />} // *
            exact
            path={`${path}/maincontent`} // <-- build nested path
            strict
          />
          <Route
            render={() => <SecondContent title={value} />} // *
            exact
            path={`${path}/secondcontent`} // <-- build nested path
            strict
          />
        </Switch>
      </div>
    </div>
  );
};

*render请注意,我通过道具而不是道具转换为渲染路线组件component。当您使用匿名函数渲染组件时,它会在每个渲染周期创建,即每次都会重新安装组件。render道具不这样做。有关更多信息,请参阅渲染方法

导航栏

修复toprop 值以正确渲染链接,从路径中删除前导“/”并渲染直接link.to值。

改变

to={`/${props.link.to}`}

to={props.link.to}

演示

编辑 cannot-code-nested-routes-with-react-router-dom-5-2-0


推荐阅读