React Router 4——处理嵌套路由的 404

React Router 4 -- handling 404 for nested routes

我有以下代码,我将在输入错误时处理嵌套路由:

<Switch>
<Route path="/" exact component={Home} />
<Route path="/sample" exact component={Sample} />
<Route path="/sample/example/:id" exact component={Example} />
<Route path="/sample/:example" exact component={Example} />
<Route component={404}/>
</Switch>

如果用户输入localhost:3000/something-wrong,它会正确显示404页面。但是,当他输入localhost:3000/sample/something-wrong的时候,什么都没有渲染! 我该如何妥善处理这个问题?

localhost:3000/sample/something-wrongpath="/sample/:example"

处理

localhost:3000/sample/example/something-wrong 将由 path="/sample/example/:id"

处理

因为您正在使用通配符,所以除了启用 Example 组件来呈现适当的消息,或者可能重定向到专用的 404 屏幕之外,您实际上无能为力。