簡體   English   中英

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"

如何解決?

似乎針對此問題提交了一個錯誤,並且正在處理 1 或 2 個開放的拉取請求。 幸運的是(或不幸的是)這些路徑在非布局路徑中工作得很好。

解決錯誤/問題之前的解決方法:

MainLayout轉換為包裝器組件並單獨包裝路由組件。 基本上使用一個children道具並在Outlet組件之前所在的位置渲染children項。

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>

編輯 react-router-v6-how-to-use-symbol-in-route

看來此錯誤已在v6.4.3中修復。 看起來行為在 v6.5 中發生了一些變化,當涉及到需要是完整段的動態路由路徑段時,例如"/:profileId"

您仍然可以使用特殊字符,但動態參數 ( :param ) 需要完整的 url 段。 6.5.0 包含一個修復程序,用於刪除對部分參數 ( /@:param ) 的無意支持。 如果您的應用程序之前依賴於此錯誤行為,則發行說明中提供了建議的方法。

這意味着路由路徑應省略特殊字符並應用正則表達式、字符串操作等來提取路徑標記值。

path="/:productSlug"

 function Product() { const { productSlug } = useParams(); const [category, product] = productSlug.split("--"); //... }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM