React router 路由容器 Switch

8 min read

在编写权限管理相关的代码前,我们需要先为所有的页面路由找到一个合适的容器,即 react-router 中的 Switch 组件。与多个独立路由不同的是,包裹在 Switch 中的路由每次只会渲染路径匹配成功的第一个,而不是所有符合路径匹配条件的路由。

<Router>
  <Route path="/about" component={About}/>
  <Route path="/:user" component={User}/>
  <Route component={NoMatch}/>
</Router>

<Router>
  <Switch>
    <Route path="/about" component={About}/>
    <Route path="/:user" component={User}/>
    <Route component={NoMatch}/>
  </Switch>
</Router>

以上面两段代码为例,如果当前页面路径是 /about 的话,因为 这三个路由的路径都符合 /about,所以它们会同时被渲染在当前页面。而将它们包裹在 Switch 中后,react-router 在找到第一个符合条件的 路由后就会停止查找直接渲染 组件。

在企业管理系统中因为页面与页面之间一般都是平行且排他的关系,所以利用好 Switch 这个特性对于我们简化页面渲染逻辑有着极大的帮助。