更新时间:2022-05-23 22:37:29
自此,状态更改时,您将调用效果.已经考虑了转换和重复索引.为了避免警告,您可以在 useEffect
Since, when state changes you will call the effect. transformations and duplicateIndexes will already be considered for. To avoid the warning, you can move the destructure
within useEffect
const { setIsValid } = props;
const [state, setState] = useState({
transformations: [],
duplicateIndexes: []
});
useEffect(() => {
const { transformations, duplicateIndexes } = state;
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]);
还将setIsValid作为useEffect的依赖项,您也不能这样做,因为在每个渲染器上都会为其创建一个新函数,这将导致useEffect一次又一次地运行,直到您稍微重构代码为止.
Also regarding setIsValid as a dependency to useEffect, you must not do that since a new function for it is created on every render and it will cause the useEffect to to run again and again unles you refactor your code a bit.
const setIsValid = useCallback((bool) => {
setState(prev => Object.assign({}, prev, {isValid: bool});
}, []);
,现在您可以将 setIsValid
设置为依赖项.
and now you can set setIsValid
as a dependency.