最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Redux useSelector filtering on object? - Stack Overflow

matteradmin3PV0评论

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

Post a comment

comment list (0)

  1. No comments so far