为什么将函数表达式传递到 useEffect 依赖数组时会创建无限循环?函数表达式不会改变组件状态,它只是引用它。
// component has one prop called => sections
const markup = (count) => {
const stringCountCorrection = count + 1;
return (
// Some markup that references the sections prop
);
};
// Creates infinite loop
useEffect(() => {
if (sections.length) {
const sectionsWithMarkup = sections.map((section, index)=> markup(index));
setSectionBlocks(blocks => [...blocks, ...sectionsWithMarkup]);
} else {
setSectionBlocks(blocks => []);
}
}, [sections, markup]);
如果标记改变了状态,我可以理解为什么它会创建一个无限循环,但它并没有简单地引用 section 属性。
对于那些寻找这个问题的解决方案的人
const markup = useCallback((count) => {
const stringCountCorrection = count + 1;
return (
// some markup referencing the sections prop
);
// useCallback dependency array
}, [sections]);
所以我不是在寻找这个问题的代码相关答案。如果可能的话,我正在寻找关于为什么会发生这种情况的详细解释。
我对为什么更感兴趣,然后只是简单地找到解决问题的答案或正确方法。
为什么在 useEffect 之外声明的 useEffect 依赖数组中传递函数会导致在所述函数中状态和道具都未更改时重新渲染。