创建数组时 React-redux 重新渲染

问题描述 投票:0回答:1

我有一个连接的组件,我想在其中检索对象数组。在我的商店中,有一个 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(...)
)
reactjs redux react-redux render react-redux-connect
1个回答
4
投票

每次调用 connect 时都会创建一个新数组:

const mapStateToProps = (state) => ({
  items: state.items.map((itemId) => state.itemsById[itemId]),
})

为了防止这种情况,请使用记忆选择器,它每次都会返回相同的数组,除非确实发生了变化。选择器是一种计算状态派生数据的方法。 Reselect 是 redux 的记忆选择器库。

© www.soinside.com 2019 - 2024. All rights reserved.