[英]How to define fallback route properly in react-router-dom
我有以下Router
定义:
<Router>
<Route exact path='/' component={Home}/>
<Route path='/about' component={About}/>
<Route path='/code' component={Code}/>
</Router>
我希望任何未映射的路由(即/foo
)重定向回根/
。
我试过<Redirect .../>
没有成功。 此外,添加没有path=
的<Route />
会导致每个页面上出现重复的组件。
只需像这样在底部放置一个重定向并使用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>
<Router>
<Switch>
// ...your routes and then
<Route path="*" render={() => <Redirect to="/" />}
</Switch>
</Router>
您需要在<Switch>
组件中执行此操作。
// IMPORT
import {
BrowserRouter as Router,
Route,
Link,
Switch,
Redirect
} from "react-router-dom";
----------
// USAGE
<Switch>
<Route path="/" exact component={Home} />
<Redirect from="/old-match" to="/will-match" />
<Route path="/will-match" component={WillMatch} />
<Route component={NoMatch} />
</Switch>
正如您从React Router Docs中看到的那样。
转变
渲染与位置匹配的第一个子
<Route>
或<Redirect>
。这与仅使用一堆 s 有何不同?
<Switch>
的独特之处在于它专门呈现一条路线。 相比之下,每个匹配位置的<Route>
都以包容性方式呈现。 考虑这段代码:<Route path="/about" component={About}/> <Route path="/:user" component={User}/> <Route component={NoMatch}/>
如果 URL 是 /about,则
<About>
、<User>
和<NoMatch>
将全部呈现,因为它们都与路径匹配。 这是设计使然,允许我们以多种方式将<Route>
组合到我们的应用程序中,例如侧边栏和面包屑、引导选项卡等。然而,有时我们只想选择一个
<Route>
进行渲染。 如果我们在 /about 我们不想也匹配 /:user (或显示我们的“404”页面)。 以下是使用 Switch 的方法:import { Switch, Route } from 'react-router' <Switch> <Route exact path="/" component={Home}/> <Route path="/about" component={About}/> <Route path="/:user" component={User}/> <Route component={NoMatch}/> </Switch>
请在所有Routes
(添加from
属性到重定向)
<Router>
<Route exact path='/' component={Home}/>
<Route path='/about' component={About}/>
<Route path='/code' component={Code}/>
<Redirect from="/" />
</Router>
我很惊讶地看到这个问题的答案都不是我认为正确的,因为它们都使用重定向,而 IMO 的用户体验很差。 如果您立即将用户重定向到 404 路由器,用户将不知道哪个 URL 不正确。
正确的答案应该是这里的 React Router 自己的文档中演示的内容。
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/old-match">
<Redirect to="/will-match" />
</Route>
<Route path="/will-match">
<WillMatch />
</Route>
<Route path="*">
<NoMatch />
</Route>
</Switch>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.