【发布时间】:2021-07-15 14:03:30
【问题描述】:
假设我们正在使用商店中名为 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,特别是 useSelector 的 Redux 文档中,它说:
当一个动作被派发时,useSelector() 会对之前的选择器结果值和当前的结果值做一个参考比较。如果它们不同,组件将被强制重新渲染。如果它们相同,则组件不会重新渲染。
这让我相信上面的比较可能等于同一件事,因为无论是一个属性改变还是整个对象,整个组件都会重新渲染。但是在我们useSelector(...state.customerProfile) 的第二种方法中,我假设如果customerProfile 的与组件无关的属性在其他地方更新,我们可能会不必要地重新渲染组件。
但是,useSelector 可能在幕后发生了更多事情,因此在跟踪对象上的单个属性与跟踪整个对象本身之间存在性能差异?
【问题讨论】:
-
@skyboyer 已更新 - 打错了,谢谢
标签: reactjs typescript performance redux react-hooks