import { shallowEqual, useSelector } from 'react-redux';
import { createSelector } from 'reselect';
import { useRef, useEffect, useState, useCallback, useMemo} from 'react';
const regionsSelector = state => state.regions;
const cellTypeSelector = state => state.cellType;
const subTypeSelector = state => state.subType;
const genesSelector = state => state.genes ? [state.genes] : [];
const backgroundColorSelector = state => state.backgroundColor;
const depthWriteSelector = state => state.depthWrite;
const radiusScaleSelector = state => state.cellRadiusScale;
const geneExpressionLevelScaleSelector = state => state.geneExpressionLevelScale;
const selectedOptionsSelector = createSelector(
regionsSelector,
cellTypeSelector,
subTypeSelector,
genesSelector,
backgroundColorSelector,
depthWriteSelector,
radiusScaleSelector,
geneExpressionLevelScaleSelector,
(selectedRegions, selectedCellTypes, selectedSubTypes, selectedGenes,backgroundColor,depthWrite,radiusScale,geneExpressionLevelScale) => ({
regions: selectedRegions,
cellTypes: selectedCellTypes,
subTypes: selectedSubTypes,
genes: selectedGenes,
backgroundColor: backgroundColor,
depthWrite: depthWrite,
radiusScale: radiusScale,
geneExpressionLevelScale: geneExpressionLevelScale,
}),
);
export default function TestComponent() {
console.log("Test Componet")
const selectedOptions = useSelector(selectedOptionsSelector,shallowEqual);
useEffect (()=> {
console.log('Selected Options:', selectedOptions.regions,selectedOptions.subTypes,selectedOptions.cellTypes,selectedOptions.genes)
},[selectedOptions.regions,selectedOptions.subTypes,selectedOptions.cellTypes,selectedOptions.genes])
useEffect (()=>{
console.log('Settings: ', )
},[selectedOptions.backgroundColor,selectedOptions.radiusScale,selectedOptions.depthWrite])
return <div><h1>testComponent</h1></div>
}
个字符
我有这个react组件来模拟我的应用程序的行为,我遇到的问题是,当只有backgroundColor,radiusScale和depthWrite时,useEffect都运行。另一方面,当[selectedOptions.regions,selectedOptions.subTypes,selectedOptions.cellTypes,selectedOptions.genes]中的仅一个改变时,则仅运行第一个useEffect。有人能解释这种行为并提供解决方案吗?
安装一次后出现问题。
1条答案
按热度按时间0yycz8jy1#
这两种效果的运行主要是因为您选择了太多的状态。你已经创建了8个状态选择器,但随后使用
useSelector
将它们合并回一个选定对象。个字符
即使您使用的是
shallowEqual
实用函数,它也不能进行足够深的相等性检查。它只检查根级别的属性。参见shallowEqual
型
如果您单独选择每个状态,则在更新不相关的状态时不会触发“其他”效果。
示例如下:
型
当“深度写入”复选框被切换时,现在当任何“设置2”状态被更新时,“选定选项1”(因为选择器的问题)以及“设置1”和“设置2”效果都被触发。“选定选项2”效果未按预期触发。
的数据