React Router v4 渲染多个路由

React Router v4 renders multiple routes

我正在创建一个 SPA,我正在尝试使用 react-router-dom 包版本 4.1.1.

在应用程序中设置路由

我的路线定义如下:

<BrowserRouter>
  <div>
    <Route exact path="/" component={Login} />
    <Route path="/login" component={Login} />
    <Route path="404" component={NotFound} />
    <Route path="*" component={NotFound} />
  </div>
</BrowserRouter>

基本上,我想设置路由,以便对未定义路由的页面的任何请求都转到 {NotFound} 组件。

如何实现? 上面的解决方案在请求 /login 页面时同时呈现 LoginNotFound 组件。

亲切的问候

这是来自 official tutorial 的示例,如何避免呈现多个路由

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>

利用Switch渲染路由的第一个匹配项,使用

前需要导入Switch
import {Switch} from 'react-router';

<BrowserRouter>
  <Switch>
    <Route exact path="/" component={Login} />
    <Route path="/login" component={Login} />
    <Route path="404" component={NotFound} />
    <Route path="*" component={NotFound} />
  </Switch>
</BrowserRouter>

根据docs

<Switch> is unique in that it renders a route exclusively. In contrast, every <Route> that matches the location renders inclusively.

Now, if we’re at /login, <Switch> will start looking for a matching <Route>. <Route path="/login"/> will match and <Switch> will stop looking for matches and render <Login>. otherwise route matches /login with /login and * and renders both the routes

但是,当使用 Switch 时,路由的顺序很重要,请确保在其他路由之后添加前缀路由。例如'/home' 必须在路由顺序中的 '/' 之后,否则,您可以使用 exact prop

 <Switch>
    <Route exact path="/" component={Login} />
    <Route path="/home" component={Home} />
  </Switch>

我认为 NotFound 页面的呈现是因为 <Route path="*" component={NotFound} /> 规则。路由器的路径 属性 接受 path-to-regexp 理解的任何有效 URL 路径。 所以 '*' 表示零个或多个参数匹配