在我的 useEffect 中,我有一个 props 依赖项(setIsValid)。当我将此依赖项添加到 useEffect 时,它会陷入无限循环。
调用子组件时的父级:
const setIsValid = (bool) => {
const tmpStateCopy = Object.assign({}, state);
tmpStateCopy.isValid = bool;
setState(tmpStateCopy);
};
return <Child
setIsValid={setIsValid}
/>
在子组件中:
const { setIsValid } = props;
const [state, setState] = useState({
transformations: [],
duplicateIndexes: []
});
const { transformations, duplicateIndexes } = state;
useEffect(() => {
const invalids = transformations.find(x => (x.value === '' || x.replaceWith === ''));
const hasDuplicates = duplicateIndexes.length > 0;
const isValid = ((invalids === undefined) && (transformations.length > 0) && !hasDuplicates);
setIsValid(isValid)
console.log('got triggered');
}, [state]);
这样代码可以工作,但我总是收到警告。
我想要的是,当状态内的值之一发生变化(转换/重复索引)时,总是会触发验证。
通过从 props 添加 setIsValid() 函数,它可以无限运行。
警告如下所示:
./src/components/UI/integrationBuilder/layoutElements/transformer/modules/ifModules/ifModule.js
Line 103: React Hook useEffect has missing dependencies: 'duplicateIndexes.length', 'setIsValid', and 'transformations'. Either include them or remove the dependency array react-hooks/exhaustive-deps
我的问题是,如何在不收到此警告的情况下保持相同的逻辑?