我有一个连接的组件,我想在其中检索对象数组。在我的商店中,有一个 id 数组和一个用于保存项目的对象,如下所示:
const state = {
items: [0, 1, 2],
itemsById: {
0: {},
1: {},
2: {},
},
}
所以使用connect
React-Redux 的函数,我在组件中执行此操作以注入正确的数组:
const mapStateToProps = (state) => ({
items: state.items.map((itemId) => state.itemsById[itemId]),
})
我的应用程序触发更新常常(我在requestAnimationFrame
),但是items
在此过程中数组不会发生变化。通过使用 React Perf 插件分析应用程序,我的连接组件似乎进行了不必要的渲染,我不明白为什么,因为items
状态不变。
我已经尝试使用重新选择来创建一个记忆选择器,但它似乎没有改变任何东西。
更新(解决方案)
当您使用通过重新选择创建的选择器时,它会起作用。我的问题出在选择器本身:我的items
数组位于一个更新非常频繁的父对象中,我选择了这个对象而不是选择items
直接数组。
不要这样做:
const parentSelector = (state) => state.parent
const itemsByIdSelector = (state) => state.itemsById
const selector = createSelector(
parentSelector,
itemsByIdSelector,
(parent, itemsById) => parent.items.map(...)
)
Do this:
const itemsSelector = (state) => state.items
const itemsByIdSelector = (state) => state.itemsById
const selector = createSelector(
itemsSelector,
itemsByIdSelector,
(items, itemsById) => items.map(...)
)