在返回空数组或对象作为回退的情况下,是否重新选择memory



假设我们有一个用createSelector 编写的选择器

const getSmth = createSelector(
getState,
state => state.items || {}
)

记忆仍然有效吗?还是每次都会重新计算,导致我们返回新的引用?据我所知,重选是否通过引用===进行相等性检查?或者重新选择将其存储到变量中,并且引用将相同?

getSmth是一个生成的选择器。getState是输入选择器,state => state.items || {}是输出选择器

如果生成的选择器被调用多次;输出";只有当提取的值发生变化时,选择器才会重新计算

计算结果(派生数据(与重新计算无关。这意味着输出选择器返回相同的引用,或者新的引用无关紧要。

createSelector确定输入选择器返回的值是否在使用引用相等的调用之间发生了更改(===(。

例如

import { createSelector } from 'reselect';
const state = { items: undefined };
const getState = (state) => state;
const getSmth = createSelector(getState, (state) => {
console.log('[getSmth] resultFunc');
return state.items || {};
});
getSmth(state);
getSmth(state);
console.assert(
getSmth.recomputations() === 1,
'should calculate once if the reference passed into the selector is the same',
);
const getSmth1 = createSelector(getState, (state) => {
console.log('[getSmth1] resultFunc');
return state.items || {};
});
const shallowCopy = (state) => ({ ...state });
getSmth1(shallowCopy(state));  // memorize input for first call
getSmth1(shallowCopy(state));  // compare input of second call with the input of first call using `defaultEqualityCheck`(`===`)
console.assert(getSmth1.recomputations() === 2, 'should caculate twice if a new reference passed into the selector');

输出:

[getSmth] resultFunc
[getSmth1] resultFunc
[getSmth1] resultFunc

最新更新