【问题标题】:React Router rendering 404 Not Found on reloadReact Router 渲染 404 Not Found on reload
【发布时间】:2020-04-14 03:23:38
【问题描述】:

我的 App.js 设置如下。

<Router>
    <Switch>
        <Route exact path="/" component={HomePage}/>
        <Route exact path="/location" component={LocationSettings}/>                      
        <Route exact path="/edit" component={Edit}/>
        <Route exact path="/changeName" component={ChangeName}/>
        <Route exact path="/testHtml" component={TestLive}/>
        <Route exact path="/content" component={Content}/>
        <Route component={NotFoundPage}/>
     </Switch>
</Router>

在 Content 组件内部,我有以下路线

 <Router>
    <Switch>
      <Route exact path={`${match.path}`}          component={SideBar}/>
      <Route exact path={`${match.path}/section1`} component={Section1}/>
      <Route exact path={`${match.path}/section2`} component={Section2}/>
      <Route exact path={`${match.path}/section3`} component={Section3}/>
      <Route exact path={`${match.path}/section4`} component={Section4}/>
    </Switch>                   
  </Router>

section1、section2 等部分呈现在左侧边栏的一小部分。它工作正常,直到我在路由到部分后重新加载页面。重新加载后,NotFoundPage 组件被渲染。但它在其他页面上正常工作。是因为嵌套吗?可能是什么问题?? 我正在使用 React-Router 5.1.2

【问题讨论】:

  • 如果你去掉内部的Router 组件有什么改变吗?
  • 尝试删除 NotFoundPage 并阅读错误反应返回。它说什么?
  • @ThetAung 如果我删除 NotFoundPage,Blanck 页面将显示而不是 NotFoundPage
  • @HenryWoody 如果我移除内部路由器组件,Sections 组件将不会被渲染并路由到 404 Not found
  • 您能提供给我们您的完整代码吗?似乎这些信息不足以提供帮助。您可以将其发布在代码沙箱中。

标签: reactjs react-router


【解决方案1】:

从父 /content 路由中删除 exact。发生的事情是 - 当您说 /content/section1 并刷新时,路由检查在父路由中开始,并且由于您提到了 exact,因此没有任何路由匹配。因此Content 组件本身不会呈现。所以它的子路由都不会被渲染。

这样做:

<Route path="/content" component={Content}/>

只要有嵌套路由,请确保父路由没有 exact 路由。

【讨论】:

  • 完成。再次感谢您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-11
  • 2017-11-12
  • 2020-07-23
  • 2013-11-11
  • 1970-01-01
  • 1970-01-01
  • 2019-01-14
相关资源
最近更新 更多