주요 문제 : 선택기 내부의 함수를 사용하여 데이터를 재 구조화하고 다른 변수를 조인하려고했습니다.이 경우에는 내 그룹과 자식을 항목으로 합 쳤지 만 문제는 함수가 무한 루프에서 매번 호출된다는 것입니다. 상태는 변경되지 않습니다.
이 선택기가 있습니다. const groups = useSelector(state => selectProductGroups(state));
기능은 다음과 같습니다.
const groups = state.PlatformsReducer.groups;
const items = state.PlatformsReducer.items;
return groups.reduce((ac, g) => {
g.items = items.filter(i => i.groupId == g.productNumber);
if (ac[g.platformId]) {
ac[g.platformId].push(g);
} else {
ac[g.platformId] = [g];
}
return ac;
}, {});
};
So when I use a useEffect to detect if the groups variable has changed the useEffect is triggered in a loop despite the variable groups still empty.
Do you know why? or How to prevent this.
I now the problem is the function in the selector, but I don't know how to prevent this case.
이것은 useSelector
후크가 내부적 으로하는 일과 관련이 있습니다 .
useSelector
선택기를 실행하고 결과가 이전에받은 결과 (참조 비교)와 동일한 지 확인합니다. 결과가 다른 경우 새 결과가 저장되고 다시 렌더링됩니다. 결과가 동일하면 이전 결과가 대체되지 않고 다시 렌더링이 트리거되지 않습니다.
이것이 의미하는 바는 스토어가 업데이트 될 때마다 상태와 관련이없는 부분이더라도 결과가 변경되었는지 확인하기 위해 복잡한 함수가 실행된다는 것입니다. 귀하의 경우에는 항상 새로운 참조이므로 항상 변경됩니다.
이를 처리하는 가장 좋은 방법은 선택기를 가능한 한 단순하게 유지하거나 reselect에서 제공하는 것과 같은 더 복잡한 메모를 사용하는 것입니다.
다음은 선택기를 간단하게 유지하면서 사용자 지정 후크를 사용하여 제품 그룹 선택을 쉽게 재사용 할 수있는 방법의 예입니다.
const useProductGroups = () => {
// Get groups from the store.
// As the selector does not create a new object it should only
// trigger a rerender when groups changes in the store.
const groups = useSelector(state => state.PlatformsReducer.groups);
// Get items from the store,
// As the selector does not create a new object it should only
// trigger a rerender when items changes in the store.
const items = useSelector(state => state.PlatformsReducer.items);
// Reduce the group collection as desired inside of a useMemo
// so that the reduction only occurs when either items or groups
// changes.
const productGroups = useMemo(() => {
return groups.reduce((ac, g) => {
g.items = items.filter(i => i.groupId == g.productNumber);
if (ac[g.platformId]) {
ac[g.platformId].push(g);
} else {
ac[g.platformId] = [g];
}
return ac;
}, {});
}, [groups, items] /* dependency array on items / groups */);
// return the calculated product groups
return productGroups;
}
그런 다음 함수 구성 요소에서 사용자 지정 후크를 사용할 수 있습니다.
const groups = useProductGroups();
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다