【问题标题】:How can handle not found page for nested routing in react router v4?如何在反应路由器 v4 中处理未找到的嵌套路由页面?
【发布时间】:2019-08-18 05:23:18
【问题描述】:

我的应用程序中有 2 个不同的部分,第一部分是站点,另一个是管理面板,在这种情况下,我使用 react 路由器 dom 嵌套路由,但我无法处理用于面板的 url 的未找到页面;例如,我希望 /dashboard/something 被重定向到未找到的页面 我的路线如下:

<Switch>
    {/* portal */}
    <Route exact path='/' component={Portal} />
    <Route path="/landing" component={Portal} />
    <Route path="/login" component={Portal} />
    <Route path="/callback" component={Callback} />
    <Route path="/activation" component={Portal} />
    <Route path="/confirmation" component={Portal} />
    <Route path="/opportunities/:id" component={Portal} />
    <Route path='/panel' component={Portal} />
    <Route path='/electiondetails/:id' component={Portal} />
    <Route path='/errors' component={Portal} />
    {/* election panel */}
    <Route path='/electionpanel' component={Portal} />
    {/* dashboard */}
    <Route path='/dashboard' component={Index} />
    <Route path='/dashboard/login' component={Index} />
    <Route path='/dashboard/cartable/requests' component={Index} />
    <Route path='/dashboard/elections-management' component={Index} />
    {/* not found */}
    <Route path="/404" component={Portal} />
    <Redirect from="/**/" to="/404"></Redirect>
</Switch>

【问题讨论】:

  • 你可以直接拥有这个 - ` ` 不需要重定向。如果在此 Route 上方没有任何路径匹配,则会显示 Portal。
  • 不幸的是它不是,门户和仪表板的环境是不同的,当 url 错误时我想要例如 /dashboard/somethingwrong 然后重定向到一个未找到的页面,但在我的应用程序中当 url 是 /dashboard /somethingwrong ,白页显示,没有加载

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


【解决方案1】:

/dashboard/something 始终与以下路由匹配:

<Route path='/dashboard' component={Index} />

因此,您将看到Index 组件。如果您需要通过此路线并显示 404 页面,则应将其标记为 exact

<Route exact path='/dashboard' component={Index} />

您也不需要重定向到那个 404 页面,只需在没有 path 的情况下输入 Route

替换

<Route path="/404" component={Portal} />
<Redirect from="/**/" to="/404"></Redirect>

<Route component={Portal} />

【讨论】:

  • 非常感谢这工作,我又有一个问题,现在我可以重定向到另一个未找到的页面吗?还是所有错误的 url 都会转到同一个 404 页面?
  • @NasrinGhelichkhani 萨拉姆!是的,这是可能的。例如,在您的 404 页面中,您可以呈现另一个重定向以导航到更具体的 404 页面。
猜你喜欢
  • 2019-02-15
  • 1970-01-01
  • 1970-01-01
  • 2017-08-13
  • 2017-05-19
  • 2017-11-05
  • 2019-02-18
  • 1970-01-01
相关资源
最近更新 更多