29

为什么将函数表达式传递到 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 依赖数组中传递函数会导致在所述函数中状态和道具都未更改时重新渲染。

4

2 回答 2

50

问题是在每个渲染周期中,markup都会重新定义。React 使用浅对象比较来确定值是否更新。每个渲染周期markup都有不同的参考。您可以使用它useCallback来记忆该功能,因此参考是稳定的。你是否为你的 linter 启用了反应钩子规则?如果你这样做了,那么它可能会标记它,告诉你原因,并提出这个建议来解决参考问题。

const markup = useCallback(
  (count) => {
    const stringCountCorrection = count + 1;
    return (
      // Some markup that references the sections prop
    );
  },
  [count, /* and any other dependencies the react linter suggests */]
);

// No infinite looping, markup reference is stable/memoized
useEffect(() => {
    if (sections.length) {
        const sectionsWithMarkup = sections.map((section, index)=> markup(index));
        setSectionBlocks(blocks => [...blocks, ...sectionsWithMarkup]);
    } else {
        setSectionBlocks(blocks => []);
    }
}, [sections, markup]);
于 2020-06-26T19:29:46.310 回答
5

为什么传递函数表达式时会创建无限循环

“无限循环”是组件一遍又一遍地重新渲染,因为markup每次组件渲染和useEffect触发重新渲染时,该函数都是一个新的函数引用(内存中的指针),因为它是一个依赖项。

正如@drew-reese 指出的那样,解决方案是使用useCallback钩子来定义你的markup函数。

于 2020-11-18T16:16:39.843 回答