我有以下Router
定义:
<Router>
<Route exact path='/' component={Home}/>
<Route path='/about' component={About}/>
<Route path='/code' component={Code}/>
</Router>
我希望任何未映射的路由(即 /foo
)重定向回根 /
.
我试过<Redirect .../>
没有成功。还添加 <Route />
没有path=
导致每个页面上都有重复的组件。
最佳答案
只需在底部放置一个重定向,如下所示,并使用 Switch
包装您的路由:
<Router>
<Switch>
<Route exact path='/' component={Home}/>
<Route path='/about' component={About}/>
<Route path='/code' component={Code}/>
// Redirect all 404's to home
<Redirect to='/' />
</Switch>
</Router>
关于reactjs - 如何在react-router-dom中正确定义后备路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56684856/