reactjs - 对象上的 useSelector() 与对象的属性相比性能更高吗?
问题描述
假设我们正在使用商店中名为 的对象处理我们的客户资料页面CustomerProfile
。
export interface ICustomerProfileState {
status: string,
customerId: number,
contactInfo: IContactInfo,
financialInfo: IFinancialInfo
};
正如我们所看到的,这个对象由一些简单的属性以及更复杂的属性组成。在CustomerProfile.tsx
页面上,我们来比较两种跟踪和更新相关属性状态的方法。第一种方法是您useSelector
在要跟踪的单个状态属性上:
const status = useSelector((state) => state.customerProfile.status)
const preferredName = useSelector((state) => state.customerProfile.contactInfo.preferredName)
const altName1 = useSelector((state) => state.customerProfile.contactInfo.alternateName1);
const altName2 = useSelector((state) => state.customerProfile.contactInfo.alternateName2);
const preferredPayment = useSelector((state) => state.customerProfile.paymentInfo.preferredPaymentMethod;
让我们将其与第二种方法进行比较——简单地跟踪对象本身:
const customerProfile = useSelector((state) => state.customerProfile);
在有关hooks的 Redux 文档中,特别是 useSelector,它说:
当一个动作被调度时, useSelector() 将对先前的选择器结果值和当前结果值进行参考比较。如果它们不同,组件将被强制重新渲染。如果它们相同,则组件不会重新渲染。
这使我相信上面的比较可能等同于同一件事,因为无论是一个属性更改还是整个对象,整个组件都会重新渲染。但是在我们的第二种方法中,我假设如果在其他地方更新useSelector(...state.customerProfile)
了与组件无关的属性,我们可能会不必要地重新渲染组件。customerProfile
但也许在幕后发生了更多事情,useSelector
以至于跟踪对象上的单个属性与跟踪整个对象本身之间存在性能差异?
解决方案
性能在这里不是问题。任何一个都可以在任何 React 应用程序中正常运行。在您拥有一个可以工作的应用程序并且可以进行分析之后,应该考虑性能。通过分析识别实际瓶颈。
至于使用哪种样式,请使用最容易阅读和维护最清晰的样式。IMO 具有解构功能的单个选择器会更好。如果分析显示这会导致不必要的重新渲染,则为每个状态组件创建单独的选择器,然后使用一个选择器将其重新组合到一个对象中,因此在组件内仍然只有一个useSelector
调用。
使用 reselect 重用和分层选择器通常是最佳实践。
推荐阅读
- javascript - 如果没有标签,如何使 Select 元素可访问?
- javascript - 如何在 Vue.js 中将 URL 传递给 iFrame
- python - 在特定区域/边界中查找特定颜色 (0x499EFF)
- dapp - 通过与 Metamask 连接的 dapp 显示我的合约代币余额
- javascript - JavaScript 可以同时执行两个异步函数或回调吗?
- java - 如何在 Java 中正确使用 Spark SQL 缓存?
- vue.js - vue-router:如何在没有“/”的情况下将查询值附加到 URL 的末尾?
- python - 如何在河内塔的每一步中添加数字
- django - 即使在 URL 中附加了斜线,Django 也会返回 301
- javascript - 在这种情况下,如何从 API 调用中控制台记录数据?