如何使用 React Router v6 创建子路由器?

Amm*_*med 8 javascript typescript reactjs react-router react-router-dom

这是我当前的 React Router 实现:

const router = createBrowserRouter([
    {
      path: "/",
      element: (
        <Page activeNav="home" >
          <Home />
        </Page>
      )
    },
    {
      path: "/about",
      element: (
        <Page activeNav="about" >
          <About />
        </Page>
      )
    },
    {
      path: "/blog",
      element: (
        <Page activeNav="blog">
          <Blog />
        </Page>
      )
    },
    {
      path: "/blog/:postName",
      element: (
        <Page activeNav="blog" >
          <Post />
        </Page>
      ),
      loader: ({ params }) => params.postName
    },
    {
      path: "/chess",
      element: <ChessRouter />
    }
  ])
Run Code Online (Sandbox Code Playgroud)

最后一条路线/chess很重要。我正在寻找定义诸如/chess/play/chess/login/chess/register等路由。我最初的想法是仅将另一个Router作为路径的元素/chess,然后所有这些路径都将从那里路由。但是,这会引发错误:

You cannot render a <Router> inside another <Router>. You should never have more than one in your app.
Run Code Online (Sandbox Code Playgroud)

我还尝试在路线上使用 Children 属性,但是当我去etc/chess时,这不会呈现任何内容。/chess/play

实现子路径的正确方法是什么(不确定正确的词)?

Dre*_*ese 12

您不能在另一个路由器组件中渲染一个路由器组件,这是正确的,因为这是一种不变的冲突。每个 React 应用程序只需要一个路由器和路由上下文。

要渲染子路线,"/chess"有两种选择:

  1. 在路由配置声明中渲染嵌套路由。这需要组件为嵌套路由ChessRouter渲染一个Outlet组件,以将其element内容渲染到其中。嵌套路由将能够使用新的 RRDv6.4 数据 API。

    const router = createBrowserRouter([
      ...,
      {
        path: "/chess",
        element: <ChessRouter />,
        children: [
          ...,
          {
            path: "play",
            element: <ChessPlay />
          },
          ... other chess sub-rotues
        ],
      }
    ]);
    
    Run Code Online (Sandbox Code Playgroud)
    const ChessRouter = () => {
      ...
    
      return (
        ...
        <Outlet />
        ...
      );
    };
    
    Run Code Online (Sandbox Code Playgroud)
  2. 渲染带有尾随通配符 ( ) 字符的根路由"*",该字符允许也匹配后代路由。这允许ChessRouter组件呈现后代路由,即Routes具有一组组件的组件Route。下降路线将无法使用 RRDv6.4 数据 API。

    const router = createBrowserRouter([
      ...,
      {
        path: "/chess/*",
        element: <ChessRouter />,
      }
    ]);
    
    Run Code Online (Sandbox Code Playgroud)
    const ChessRouter = () => {
      ...
    
      return (
        ...
        <Routes>
          ...
          <Route path="/play" element={<ChessPlay />} />
          ... other chess sub-rotues
        </Routes>
        ...
      );
    };
    
    Run Code Online (Sandbox Code Playgroud)