【问题标题】:Why wrap the routes around the <Switch> component in react-router when they work just fine without it?为什么在 react-router 中将路由包裹在 <Switch> 组件周围,如果没有它就可以正常工作?
【发布时间】:2021-04-29 17:55:15
【问题描述】:

使用react-router-dom 5.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>
)

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

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

【问题讨论】:

    标签: javascript reactjs react-router react-router-dom


    【解决方案1】:

    这其实是在documentation中回答的:

    这与只使用一堆&lt;Route&gt;s 有何不同?

    &lt;Switch&gt; 的独特之处在于它专门呈现一条路线。相比之下,与该位置匹配的每个 &lt;Route&gt; 都会以包容性方式呈现。

    因此,在您的情况下,当您转到 /route1 时,如果您删除了 SwitchRoute1Component OtherRouteComponent 都会呈现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-11
      • 2013-11-05
      • 2022-12-20
      • 2020-05-11
      • 2019-02-26
      相关资源
      最近更新 更多