React Router v6 - 如何处理嵌套路由但只显示当前页面而不是以前的页面

React Router v6 - how to handle nested routes but with only current page showing instead of previous pages

我正在尝试了解如何使用 react-router v6 处理不同页面的嵌套路由。

例如,说“/”路径returns公司列表。 “:companyId”带你到公司页面,“:/productId”带你到该公司的产品。

我想知道的是如何只显示该产品的内容页面,而不是同时显示产品列表和公司列表。

我认为这应该是嵌套的,因为我需要公司 ID 和产品 ID 的基础参数才能知道我在哪里。这种情况下如何正确使用Outlet?

Companies 有一个公司列表。公司有产品清单。

我目前的路线:

const routes = [
  {
    path: "/",
    element: <Companies />,
    children: [
      {
        path: ":companyId",
        element: <Company />,
        children: [{ path: ":productId", element: <Product /> }],
      },
    ],
  },
]

const routes = [
  {
    path: "/",
    children: [
      {
        index: true,
        element: <Companies />,
      },
      {
        path: ":companyId",
        children: [
          { index: true, element: <Company /> },
          { path: ":productId", element: <Product /> },
        ],
      },
    ],
  },
];

如果我对你的 question/issue 理解正确,那么 Companies 似乎是作为布局组件呈现的,换句话说,它是与嵌套的子路由一起呈现的,但你想要一个或另一个。

如果你想渲染一个或另一个然后将 Companies 向下移动到子路由中,特别是作为索引路由,所以当路径正好是 "/" 时渲染它而不是当另一个嵌套路由匹配。

const routes = [
  {
    path: "/",
    children: [
      {
        index: true,
        element: <Companies />,
      },
      {
        path: ":companyId",
        element: <Company />,
        children: [
          {
            path: ":productId",
            element: <Product />
          }
        ],
      },
    ],
  },
]