gpt4 book ai didi

reactjs - 如何在react-router-dom中正确定义后备路由

转载 作者:行者123 更新时间:2023-12-03 13:56:39 25 4
gpt4 key购买 nike

我有以下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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com