簡體   English   中英

如何指定 react-router-dom 路由以進行匹配?

[英]How to specify react-router-dom routes in order for matching?

我使用具有指定版本的以下依賴項進行反應

{
  "react-router-dom": "^5.2.0",
  "react-dom": "^16.14.0",
}

我想要一條這樣的路線

  • 關於
  • 首頁/測試
  • 主頁/測試/新 <== 這是我的問題

我有

<BrowserRouter>
    <Switch>
        <PublicRoute  component={Login} path="/" exact />
        <PublicRoute  component={Login} path="/login" exact />
        <PrivateRoute component={Dashboard} path="/dashboard"/>
        <Route to="/404" component={NotFound} />
    </Switch>
</BrowserRouter>

在儀表板上我有這個

<Router>
    <Navbar />
    <Switch>
        <Route path={`/dashboard/buyList`} component={BuyList} />
        <Route exact path='/dashboard/buyList/new' component={NewBuy} />
        <Route path={`/dashboard/buyList${ids.id}`} component={BuyInfo}/>
        <Route path='/dashboard/showAddress' component={ShowAddress} exact/>
        <Route path='/dashboard/qrScanner' component={QrScanner} exact/>
        <Route path='/dashboard/productList' component={ProductList} exact/>
        <Route path='/dashboard/productListCode' component={ProductListCode} exact/>
        <Route path='/dashboard/deliveryScanner' component={DeliveryScanner} exact/>
        <Route path='/dashboard' component={DashboardDetail} exact/>
        <Route path="/404" component={NotFound} />
    </Switch>
</Router>

但是在"/dashboard/buyList/new"正在加載"/dashboard/buyList"的組件

您可以將exact參數添加到/dashboard/buyList

<Switch>
    <Route path= '/dashboard/buyList' component={BuyList} exact />
    <Route exact path='/dashboard/buyList/new' component={NewBuy} />
    //other routes
<Switch>

問題

  1. 您只需要一個路由器,因此請移除儀表板路由周圍的嵌套Router
  2. 在任何地方添加exact道具並不是靈丹妙葯。 在這里不一定能正確解決您的問題。 Switch組件僅呈現它找到的第一個匹配項,即使您真正想要匹配和呈現的匹配項位於“列表”的后面。 在這種情況下,“/dashboard/buyList”不如“/dashboard/buyList/new”具體,但因為它是實際路徑“/dashboard/buyList/new”的前綴,所以它被匹配和呈現。

解決方案

刪除無關的Router 確保您已指定從最具體到最不具體的路由路徑。 如果訂購正確,則絕對不需要exact道具。

"/dashboard/buyList/new""/dashboard/buyList${ids.id}""/dashboard/buyList"更具體,等等。

此外,從 404 路由中刪除path道具,以便在其上方沒有其他路由匹配的情況下也可以正確匹配和呈現。

<Navbar />
<Switch>
  <Route path='/dashboard/buyList/new' component={NewBuy} />
  <Route path={`/dashboard/buyList${ids.id}`} component={BuyInfo} />
  <Route path='/dashboard/buyList' component={BuyList} />
  <Route path='/dashboard/showAddress' component={ShowAddress} />
  <Route path='/dashboard/qrScanner' component={QrScanner} />
  <Route path='/dashboard/productList' component={ProductList} />
  <Route path='/dashboard/productListCode' component={ProductListCode} />
  <Route path='/dashboard/deliveryScanner' component={DeliveryScanner} />
  <Route path='/dashboard' component={DashboardDetail} />
  <Route component={NotFound} />
</Switch>

暫無
暫無

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

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