javascript - Redux useSelector filtering on object? - Stack Overflow

So I'm using redux and useSelector hook to get data from store.I can filter specific data in a re

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744307610a4567792.html

相关推荐

  • javascript - Redux useSelector filtering on object? - Stack Overflow

    So I'm using redux and useSelector hook to get data from store.I can filter specific data in a re

    7天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信