[英]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>
Router
。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.