首页 > 解决方案 > 为什么要围绕react-router 中的组件在没有它的情况下可以正常工作吗?

问题描述

使用react-router-dom5.2.0 来获得它的价值。

按照习惯,我倾向于将所有Route组件都包裹在一个Switch组件中。

例子:

const MyRoutes = () => (
  <Switch>
    <Route
      path='/route1'
      exact
      component={() => <Route1Component />}
    />
    <Route
      path={[
        '/route2',
        '/route2/subroute',
        '/route2/subroute2',
      ]}
      exact
      component={() => <Route2Component />}
    />
    <Route
        path='*'
        exact
        component={() => <OtherRoutesComponent />}
      />
  </Switch>
)

但我已经意识到没有它的工作没有任何区别。

所以我的问题是,为什么要全部使用它?它有什么好处或坏处吗?

标签: javascriptreactjsreact-routerreact-router-dom

解决方案


这实际上在文档中得到了回答:

这与仅使用一堆<Route>s 有何不同?

<Switch>独特之处在于它专门渲染一条路线。相反,<Route>与位置匹配的每一个都以包容性方式呈现。

因此,在您的情况下,当您转到 时/route1,如果您删除了.Route1Component OtherRouteComponentSwitch


推荐阅读