javascript - 为什么要围绕react-router 中的组件在没有它的情况下可以正常工作吗?
问题描述
使用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>
)
但我已经意识到没有它的工作没有任何区别。
所以我的问题是,为什么要全部使用它?它有什么好处或坏处吗?
解决方案
这实际上在文档中得到了回答:
这与仅使用一堆
<Route>
s 有何不同?
<Switch>
独特之处在于它专门渲染一条路线。相反,<Route>
与位置匹配的每一个都以包容性方式呈现。
因此,在您的情况下,当您转到 时/route1
,如果您删除了.Route1Component
OtherRouteComponent
Switch
推荐阅读
- android - 如何使用cordova在android手机中获取当前设置的声音
- r - 使用 R 中的新列对总和和排名进行排序和计算
- spring - Spring 的基本安全覆盖应用程序的配置
- apache-spark - 为什么我在 Spark Master 上收到“正在移除工作人员,因为我们在 60 秒内没有心跳”
- msbuild - 跟踪 MsBuild 工具链脚本的执行
- r - R中的总和(非相邻)行
- php - 验证码验证不起作用
- android - 在用 kotlin 编写的 Modulair Android 项目中初始化 Firebase 时出现未初始化错误
- tensorflow - 如何从一个类中制作两个卷积网络并进行权重共享[Siamese net]
- python - 从网站提取文本时出错:AttributeError 'NoneType' 对象没有属性 'get_text'