如何处理 react router v4 中嵌套路由的未找到页面?

How can handle not found page for nested routing in react router v4?

我的应用程序中有 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>

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

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

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

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

此外,您不需要重定向到该 404 页面,只需放置一个没有 pathRoute:

替换

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

<Route component={Portal} />