繁体   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