最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Redux useSelector filtering on object? - Stack Overflow

programmeradmin6浏览0评论

So I'm using redux and useSelector hook to get data from store.

I can filter specific data in a reducer array, so that the ponent only updates when the filtered data is changed, for example:

const images = useSelector(state => state.Reducer.images.filter(x => x.id === someID));

However, when I try the same sort of thing with an object, the ponent always re-renders even if the store hasn't even changed. e.g.:

const images = useSelector(state => Object.keys(state.Reducer.images)
  .filter(x => x === someID)
  .reduce((arr, key) => {
    arr.push(state.Reducer.images[key].data);
    return arr;
  }, []));

Why is this happening and how do I get it only to update when the data has changed? Am assuming passing some deep parison function into useSelector?

So I'm using redux and useSelector hook to get data from store.

I can filter specific data in a reducer array, so that the ponent only updates when the filtered data is changed, for example:

const images = useSelector(state => state.Reducer.images.filter(x => x.id === someID));

However, when I try the same sort of thing with an object, the ponent always re-renders even if the store hasn't even changed. e.g.:

const images = useSelector(state => Object.keys(state.Reducer.images)
  .filter(x => x === someID)
  .reduce((arr, key) => {
    arr.push(state.Reducer.images[key].data);
    return arr;
  }, []));

Why is this happening and how do I get it only to update when the data has changed? Am assuming passing some deep parison function into useSelector?

Share Improve this question asked Mar 14, 2021 at 15:01 Jon FlynnJon Flynn 4608 silver badges23 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

You should be able to avoid these re-renders by using shallowEqual. This will prevent the new references from being considered different all the time.

const images = useSelector(state => Object.keys(state.Reducer.images)
  .filter(x => x === someID)
  .reduce((arr, key) => {
    arr.push(state.Reducer.images[key].data);
    return arr;
  }, []), shallowEqual);

https://react-redux.js/api/hooks#equality-parisons-and-updates

发布评论

评论列表(0)

  1. 暂无评论