创建数组时React-redux重新渲染 [英] React-redux rerenders when creating arrays

查看:126
本文介绍了创建数组时React-redux重新渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个连接的组件,我想在其中检索对象数组。在我的商店中,有一个ID数组,还有一个对象,我用来存放这样的物品:

I have a connected component where I would like to retrieve an array of objects. In my store, there is an array of ids, and an object where I keep the items like this:

const state = {
  items: [0, 1, 2],
  itemsById: {
    0: {},
    1: {},
    2: {},
  },
}

因此,使用 connect react-redux函数,我在组件中执行此操作以注入正确的数组:

So using the connect function of react-redux, I do this in my component to inject the correct array:

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

我的应用经常触发更新(我在 requestAnimationFrame 中调度动作),但 items 数组在此过程中不会更改。通过使用React Perf插件分析应用程序,似乎我的连接组件进行了不必要的渲染,而且我不明白为什么原因,因为状态中的 items 不变

My app triggers updates very often (I dispatch actions in requestAnimationFrame), but the items array do not change during the process. By analyzing the app with the React Perf addon, it seems that my connected component makes unnecessary rendering, and I don't understand why because the items in the state don't change.

我已经尝试过使用reselect来创建一个记忆选择器,但是似乎没有任何改变。

I already tried to make a memoized selector using reselect but it seems it does not change anything.

当您使用通过重新选择创建的选择器时,它可以工作。我的问题出在选择器本身:我的项目数组位于一个父对象中,该对象经常更新,而我选择该对象而不是选择项目数组。

It works when you use a selector created with reselect. My problem was in the selector itself: my items array is located in a parent object which updates very frequently, and I was selecting this object instead of selecting the items array directly.

不要这样做:

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调用时,您都在创建一个新数组这样做:

You are creating a new array every time connect is called by doing this:

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

为防止这种情况,请使用记忆选择器,每次都会返回相同的数组,除非实际更改。选择器是一种从状态计算派生数据的方法。 重新选择是用于redux的记忆选择器库。

To prevent that use a memoized selector, which will return the same array every time, unless something actually changed. A selector is a method that computes the derived data from the state. Reselect is a memoized selector library for redux.

这篇关于创建数组时React-redux重新渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆