我有一个关于重新 Select 的 Select 器记忆的问题.

就我对Reselect文档的理解而言,以下实现是建议的正确方法,用于记忆需要参数的 Select 器:

const selectOrdersByCustomer = createSelector(
    [
        state => state.orders,
        (state, customerId) => customerId,
    ],
    (orders, customerId) => {
        return orders.filter(order => order.customerId === customerId);
    }
);
const orders = useSelector(state => selectOrdersByCustomer(state, customerId));

我的一位同事提出了同样的 Select 者的方法:

const selectOrdersByCustomer = customerId => createSelector(
    state => state.orders,
    orders => {
        return orders.filter(order => order.customerId === customerId);
    }
);
const orders = useSelector(selectOrdersByCustomer(customerId));

(我简化了这一点,我们应用程序中的实际实现要复杂得多)

我try 将console.count('counter');添加到使用此 Select 器的组件中,两种实现似乎都会触发相同数量的重现.

我的问题是:与第一个实现相比,第二个实现是否会对性能造成影响?

推荐答案

第二种方法存在性能问题.每个 Select 器都有自己的缓存结果,但每次组件呈现时都会创建一个新的带记忆的 Select 器函数.它将多次运行输出 Select 器.不会使用缓存的结果.

import { createSelector } from 'reselect';

const selectOrdersByCustomer1 = createSelector(
    [(state) => state.orders, (state, customerId) => customerId],
    (orders, customerId) => {
        console.count('selectOrdersByCustomer1 output selector');
        return orders.filter((order) => order.customerId === customerId);
    },
);

const selectOrdersByCustomer2 = (customerId) =>
    createSelector(
        (state) => state.orders,
        (orders) => {
            console.count('selectOrdersByCustomer2 output selector');
            // @ts-ignore
            return orders.filter((order) => order.customerId === customerId);
        },
    );

const state = { orders: [{ customId: 1 }, { customId: 2 }] };
const x1 = selectOrdersByCustomer1(state, 1);
const x2 = selectOrdersByCustomer1(state, 1);
const x3 = selectOrdersByCustomer1(state, 1);
console.log(selectOrdersByCustomer1.recomputations());
console.log(x1 === x2, x1 === x3);

const s1 = selectOrdersByCustomer2(1)(state);
const s2 = selectOrdersByCustomer2(1)(state);
const s3 = selectOrdersByCustomer2(1)(state);
console.log(s1 === s2, s1 === s3);

日志(log):

selectOrdersByCustomer1 output selector: 1
1
true true
selectOrdersByCustomer2 output selector: 1
selectOrdersByCustomer2 output selector: 2
selectOrdersByCustomer2 output selector: 3
false false

Javascript相关问答推荐

如何使用侧边滚动按钮具体滚动每4个格?

如何从JSON数组添加Google Maps标记—或者如何为数组添加参数到标记构造器

类型自定义lazy Promise. all

如何使覆盖div与可水平滚动的父div相关?

在nextjs服务器端api调用中传递认证凭证

如何在文本字段中输入变量?

将核心模块导入另一个组件模块时存在多个主题

Next.js服务器端组件请求,如何发送我的cookie token?

在浏览器中触发插入事件时检索编码值的能力

扩展类型的联合被解析为基类型

SPAN不会在点击时关闭模式,尽管它们可以发送日志(log)等

为什么当我更新数据库时,我的所有组件都重新呈现?

P5.js中的分形树

Next.js无法从外部本地主机获取图像

FireBase FiRestore安全规则-嵌套对象的MapDiff

React Refs不与高阶组件(HOC)中的动态生成组件一起工作

为什么我的Navbar.css没有显示在本地主机页面上?

将延迟加载的模块转换为Eager 加载的模块

在Press Reaction本机和EXPO av上播放单个文件

在使用JavaScript以HTML格式显示Google Drive中的图像时遇到问题