如何在 react-router-dom 中正确定义回退路由 [英] How to define fallback route properly in react-router-dom
本文介绍了如何在 react-router-dom 中正确定义回退路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下 Router
定义:
<Router>
<Route exact path='/' component={Home}/>
<Route path='/about' component={About}/>
<Route path='/code' component={Code}/>
</Router>
我希望任何未映射的路由(即 /foo
)重定向回根 /
.
I want any unmapped route (i.e /foo
) to redirect back to root /
.
我尝试了
没有成功.还添加一个
而没有 path=
导致每个页面上都有重复的组件.
I tried <Redirect .../>
without success. Also adding a <Route />
without a path=
resulted in a duplicated component on each page.
推荐答案
只需像这样在底部放置一个重定向并用 Switch
包裹你的路由:
Just place a redirect at the bottom like this and wrap your routes with 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>
这篇关于如何在 react-router-dom 中正确定义回退路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文