我有以下
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>
<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>
但是,有时我们只想选择一个
进行渲染。如果我们位于 /about,我们不想也匹配 /:user (或显示我们的“404”页面)。以下是使用 Switch 进行操作的方法:<Route>
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>
我很惊讶地发现这个问题的答案都不是我认为正确的,因为它们都使用重定向,在我看来这是一种糟糕的用户体验。 如果您立即将用户重定向到 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>
请在所有
Routes
底部添加默认路由(添加from
属性进行重定向)
<Router>
<Route exact path='/' component={Home}/>
<Route path='/about' component={About}/>
<Route path='/code' component={Code}/>
<Redirect from="/" />
</Router>
在 React Router v6 中,Redirect 组件已被 Navigate 组件替换。因此,您应该使用这样的 Navigate 组件,而不是使用 Redirect to="/":
<Routes>
{/* Define your other routes here */}
<Route path="/home" element={<Home />} />
{/* Redirect to /home */}
<Route path="*" element={<Navigate to="/home" replace />} />
</Routes>