我有一个连接的组件,我想在其中检索对象数组。在我的商店中,有一个 id 数组,以及一个用于保存物品的对象,如下所示:
const state = {
items: [0, 1, 2],
itemsById: {
0: {},
1: {},
2: {},
},
}
因此,使用react-redux的
connect
函数,我在组件中执行此操作以注入正确的数组:
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(...)
)
这样做:
const itemsSelector = (state) => state.items
const itemsByIdSelector = (state) => state.itemsById
const selector = createSelector(
itemsSelector,
itemsByIdSelector,
(items, itemsById) => items.map(...)
)