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 badges1 Answer
Reset to default 6You 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
评论列表(0条)