首页 > 解决方案 > 对象上的 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以至于跟踪对象上的单个属性与跟踪整个对象本身之间存在性能差异?

标签: reactjstypescriptperformancereduxreact-hooks

解决方案


性能在这里不是问题。任何一个都可以在任何 React 应用程序中正常运行。在您拥有一个可以工作的应用程序并且可以进行分析之后,应该考虑性能。通过分析识别实际瓶颈。

至于使用哪种样式,请使用最容易阅读和维护最清晰的样式。IMO 具有解构功能的单个选择器会更好。如果分析显示这会导致不必要的重新渲染,则为每个状态组件创建单独的选择器,然后使用一个选择器将其重新组合到一个对象中,因此在组件内仍然只有一个useSelector调用。

使用 reselect 重用和分层选择器通常是最佳实践。


推荐阅读