React:如何防止在useEffect中调用的函数超过最大更新深度



我得到这个错误:

超过最大更新深度。这可能发生当一个组件调用setState在useEffect中,但是useEffect没有依赖项数组,或者其中一个依赖项在每次渲染时发生变化。

我有这样的状态:

const [arrayOfDocuments, setArrayOfDocuments] = useState([]);

存储类型为document

的对象将文档添加到状态的函数:

const pushToArrayOfDocuments = (obj) => {
if (obj.filename && obj.file && obj.expiredate && obj.doctype) {
setArrayOfDocuments((oldArr) => {
const arr = oldArr.slice();
const index = arr.map((e) => e.filename).indexOf(obj.filename);
if (index !== -1) {
arr[index] = obj;
} else {
arr.push(obj);
}
return arr;
});
}
};

现在这个函数开始传递给子组件:

像这样:

<OperatorDocument
key={`Visura camerale${count}`}
title="Visura camerale"
setDocument={pushToArrayOfDocuments}
description=" in dolor."
document={getObjectByName('Visura camerale')}
filedocname="Visura camerale"
/>

现在在子组件中我有这样的状态:

const [file, setFile] = useState(document);

现在,如果这个状态改变,我调用setDocument在useEffect

useEffect(() => {
setDocument(file);
}, [file, setDocument]);

,现在我得到了错误。有什么办法可以预防吗?

错误已经告诉你这个问题,因为setState是在数组依赖项中,组件每次更新。

试试这个删除setDocument并在依赖数组中只保留file,这样它只在文件更改时更新

Like this [file]

最新更新