【问题标题】:Nested navigation with params is not working in react-router-dom带有参数的嵌套导航在 react-router-dom 中不起作用
【发布时间】:2020-01-13 11:26:28
【问题描述】:

我正在尝试在我的应用程序中使用嵌套路由。在这种情况下,商店页面位于 /shop 网址上,我想在 /shop/CollectionPage 上呈现 CollectionsOverview > 在 /shop/:collection 上,CollectionsOverview 工作正常,但 CollectionPage 不工作。我什至尝试使用像 /shop/abc 这样的硬编码路径,但它仍然无法正常工作..请帮助

我的 react-router-dom 版本是 ^5.0.0

import React from 'react';
import {Route, Switch,Router} from 'react-router-dom';


function CollectionPage() {
  return (
    <div className="App">
      CollectionPage
    </div>
  );
}

function CollectionsOverview() {
  return (
    <div className="App">
      CollectionsOverview
    </div>
  );
}

 export default function ShopPage({match}){
return(
  <div className='shop-page'>
    <Router>
  <Switch>
    <Route exact path={`${match.path}`} component={CollectionsOverview}/>
    <Route exact path={`${match.path}/:collectionId `} component={CollectionPage}/>
    </Switch>
    </Router>
  </div>
)
}

【问题讨论】:

  • 尝试从第二条路由CollectionPage中删除exact
  • 我已经尝试删除这两个。
  • 你在更高级别的组件中还有其他RouterSwitch,自然是App.js 吗?
  • 为什么会有2个CollectionPage功能组件?我想第二个一定是CollectionsOverview
  • @SultanH。是的,我在 App.js 中有路由器

标签: reactjs react-router react-router-dom


【解决方案1】:

试试这个,因为你已经有一个 Router 包装你的 App 组件,你不需要另一个在 ShopPage 中拥有它自己的上下文,因为它 -supposedly- 最初是从 App 路由的,在 Router 的上下文中,它位于 App

export default function ShopPage({match}){
  return (
    <div className='shop-page'>
      <Switch>
        <Route exact path={`${match.path}`} component={CollectionsOverview}/>
        <Route exact path={`${match.path}/:collectionId `} component={CollectionPage}/>
      </Switch>
    </div>
  );
}

您只需要Switch 来确定它的Route 组件的导航决​​策

【讨论】:

  • 你有理由为什么使用${math.path} 而不是shop
  • 对不起match.path in path={${match.path}/:collectionId}}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-04
  • 2023-01-30
  • 2021-12-24
  • 2019-10-21
  • 2020-06-02
  • 1970-01-01
相关资源
最近更新 更多