【问题标题】:Using multiple react router switch throws 404 error使用多个反应路由器开关会引发 404 错误
【发布时间】:2020-08-09 18:10:49
【问题描述】:

我正在尝试根据视图分隔我的路线。具体来说,我创建了一个管理员视图,其中我将为管理员提供不同的路线。我正在尝试使用多个开关,但我不断收到 404。

以下是我的做法:

App.js

<div className="App">
    <Switch>
        <Route exact path="/admin/dashboard" component={ AdminPanel } />
        <Route component={ NoMatch } />
    </Switch>
</div>

AdminPanel.js

<Link to="/admin/dashboard" className="sidebar-item">...</Link>
<Link to="/admin/dashboard/exams" className="sidebar-item">...</Link>
.
.
.
<div className="admin-content">
    <Switch>
        <Route exact path="/admin/dashboard" component={ Dashboard } />
        <Route exact path="/admin/dashboard/exams" component={ Exam } />
    </Switch>
</div>

当我访问localhost:3000/admin/dashboard 时,我看到了Dashboard 组件。但是当我导航到localhost:3000/admin/dashboard/exams 时,我会看到 404 页面。

我哪里错了?

【问题讨论】:

  • @MonzoorTamal 这个例子不是和我做的差不多吗?
  • 是的。请阅读那些cmets。您需要删除确切的。
  • 我读过,但是当特定路线不存在时怎么办?它应该转到 404 页面,但它没有。
  • 对 404 使用 path='*'

标签: javascript reactjs react-router-dom


【解决方案1】:

App.js:


<Switch>
    <Route path="/admin/dashboard" component={ AdminPanel } />
    <Route path="/404" component={ NoMatch } />
    <Route component={ NoMatch } />
</Switch>

AdminPanel.js

import {Redirect} from 'react-router-dom'

<Switch>
    <Route exact path="/admin/dashboard" component={ Dashboard } />
    <Route exact path="/admin/dashboard/exams" component={ Exam } />
    <Route render={({location}) => <Redirect to={{
      pathname: '/404',
      state: { originalUrl: location.pathname}
    }} />} />
</Switch>

稍后在NoMatch组件中,可以在props.location.state.originUrl下访问

【讨论】:

  • 它似乎确实可以解决问题!但我有两个问题:1)如果我想保留导致 404 的 URL 怎么办? 2) 有没有一种方法可以让我不必明确提及重定向到 404?
  • 使用 &lt;Route component={ NoMatch } /&gt; 在管理内容容器中呈现 404 页面。重定向按我想要的方式工作。
  • 有没有办法只提到 404 来处理所有不匹配的情况?以及如何保留未找到网址的网址
  • 访问props.location.state.originUrl后该怎么办?
  • 那么你可以按照“如果我想保留导致 404 的 URL 怎么办”的意思做任何事情
猜你喜欢
  • 2023-01-21
  • 2018-09-13
  • 1970-01-01
  • 2018-11-30
  • 2021-05-16
  • 2021-03-01
  • 2018-09-20
  • 2017-12-20
相关资源
最近更新 更多