创建数组时 React-redux 重新渲染 [英] React-redux rerenders when creating arrays
问题描述
我有一个连接组件,我想在其中检索一组对象.在我的商店中,有一个 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: {},
},
}
所以使用 react-redux 的 connect
函数,我在我的组件中这样做以注入正确的数组:
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.
当您使用通过重新选择创建的选择器时,它会起作用.我的问题出在选择器本身:我的 items
数组位于更新非常频繁的父对象中,我选择了这个对象,而不是直接选择 items
数组.
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]),
})
为了防止这种情况,请使用 记忆化选择器,它将返回相同的数组每次,除非确实发生了变化.选择器是一种从状态计算派生数据的方法.Reselect 是 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屋!