我有一个连接的组件,我想在其中检索对象数组。在我的商店中,有一个 id 数组和一个用于保存项目的对象,如下所示:
const state = {
items: [0, 1, 2],
itemsById: {
0: {},
1: {},
2: {},
},
}
因此,使用react-redux的connect
函数,我在组件中执行此操作以注入(inject)正确的数组:
const mapStateToProps = (state) => ({
items: state.items.map((itemId) => state.itemsById[itemId]),
})
我的应用经常触发更新(我在 requestAnimationFrame
中分派(dispatch)操作),但 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(...)
)
最佳答案
每次调用 connect 时,您都会创建一个新数组,方法如下:
const mapStateToProps = (state) => ({
items: state.items.map((itemId) => state.itemsById[itemId]),
})
为了防止这种情况,请使用 memoized selector ,每次都会返回相同的数组,除非确实发生了变化。选择器是一种计算状态派生数据的方法。 Reselect是一个用于 redux 的内存选择器库。
关于reactjs - React-redux 创建数组时重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39062188/