Selectors are efficient. A selector is not recomputed unless one of its arguments changes.
我正在尝试调试比预期更频繁调用的选择器。有没有办法记录为什么重新计算特定选择器(即更改了哪个参数)?
例子:
export const totalSelector = createSelector(
[subtotalSelector, taxSelector]
(subtotal, tax) => ({ total: someExpensiveCalculation(subtotal, tax) })
)
现在假设 totalSelector
的返回值作为 result
属性通过 mapStateToProps
提供给某个组件。 why-did-you-render
报告由于更改了 result
的引用(而非值)而导致不必要的渲染。因此我知道 totalSelector
必须重新计算并且我们从文档中知道它只在其输入更改时发生(subtotal
或 tax
在例子)。我如何判断触发更改的是 subtotal
还是 tax
或两者?
为了便于说明,我们假设 subtotal
和 tax
都是对象,因此它们通过引用传递。
最佳答案
这是 createSelector
的简单替代品,它将记录第一个更改的参数值:
const createDebugSelector = createSelectorCreator(defaultMemoize, {
equalityCheck: (previousVal, currentVal) => {
const rv = currentVal === previousVal;
if (!rv) console.log('Selector param value changed', currentVal);
return rv;
},
});
关于javascript - 重新选择 - 如何找出哪个参数发生了变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59376392/