解决react-hooks/exhaustive-deps警告的最佳方法

Cog*_*Cog 9 reactjs eslint react-hooks

考虑这个人为的代码片段。

const foo = () => {return 1;} 
const bar = useMemo(() => {return foo();}, [foo])
Run Code Online (Sandbox Code Playgroud)

当我触发react-hooks/exhaustive-deps警告时,我会收到这样的消息。

The 'foo' function makes the dependencies of useMemo Hook (at line 2) change on every render. Move it inside the useMemo callback. Alternatively, wrap the definition of 'foo' in its own useCallback() Hook.

该警告给了我 2 个建议:1)将 useMemo 回调引入foo内部 bar,或者 2)将函数包装在 useCallback 中。

我当然可以做任何一个。我只是想知道:这两种选择中的任何一种都比另一种更可取吗?如果是,那么为什么?如果你的答案是“这取决于”,那么它到底取决于什么?

Zac*_*ber 11

两种方法都很好用。偏好取决于代码以及您使用它们执行的操作。

例如,如果您foo在多个位置使用,则将其移动到useMemo回调内部将不起作用。

如果您仅在 useMemo 回调中使用foo,那么在其中定义它是有意义的。

在这种情况下,它看起来像:

const bar = useMemo(() => {
  const foo = () => 1;
  return foo();
  // include foo's dependencies in the deps array
}, []);
Run Code Online (Sandbox Code Playgroud)

或者你可以内联定义它:

const bar = useMemo(() => {
  return 1;
  // include foo's dependencies in the deps array
}, []);
Run Code Online (Sandbox Code Playgroud)