React Router v6 - 如何在路由中使用@符号?

React Router v6 - How to use @ symbol in route?

我正在使用 react-router-dom 来管理我的路线:

<Routes>
    <Route path="/" element={<MainLayout />}>
        <Route index element={<Home />} />
        <Route path="@:profileId" element={<Profile />} />
    </Route>
<Routes>

我想在配置文件路由中使用@前缀,但错误是no routes matched location "/@username"

如何解决?

似乎有一个 bug 提交了这个问题,并且有 1 或 2 个开放的拉取请求正在处理中。幸运的是( 或不幸的是 )这些路径在 non-layout 路由中工作正常。

bug/issue 解决之前的解决方法:

MainLayout 转换为包装器组件并单独包装路由组件。基本上使用 children 道具并渲染 children 之前 Outlet 组件所在的位置。

示例 MainLayout 布局组件:

const MainLayout = () => (
  <>
    <h1>MainLayout</h1>
    <Outlet />
  </>
);

变成

const MainLayout = ({ children }) => (
  <>
    <h1>MainLayout</h1>
    {children}
  </>
);

以及来自

的路线
<Routes>
  <Route path="/" element={<MainLayout />}>
    <Route index element={<Home />} />
    <Route path="@:profileId" element={<Profile />} />
  </Route>
</Routes>

<Router>
  <Routes>
    <Route
      path="/"
      element={
        <MainLayout>
          <Home />
        </MainLayout>
      }
    />
    <Route
      path="/@:profileId"
      element={
        <MainLayout>
          <Profile />
        </MainLayout>
      }
    />
  </Routes>
</Router>