首页 > 解决方案 > 我们在 useEffect 中使用的所有变量都在依赖项数组中吗?

问题描述

我知道 useEffect 的依赖项是如何工作的。但是在我的场景中,我不应该看到 prop 值的变化,我将其用作处理流程的条件,但如果我不将其放入依赖项数组中,我将收到 react-hooks/exhaustive-deps 警告。

我的情况是,如果 foo 和 fetchValue 发生变化,我想重新运行整个 fetch。虽然我使用 bar 作为条件来决定调用的是 fechValue,但在我的业务逻辑中,bar 的更改不应该使重新运行块。

const Component = ({ foo, bar, fetchValue }) => {
  useEffect = (
    () => {
      if(foo) {
        if (bar) {
          fetchValue();
        }
      }
    },
    [foo, fetchValue] // will get a warning `react-hooks/exhaustive-deps`
  )

  return <div />

}

标签: reactjsreact-hooks

解决方案


ESLint 规则的存在是为了提供useEffect钩子的安全性。

如果您绝对确定该值不是 的依赖项useEffect,则可以添加注释以忽略 ESLint 规则:Disabling Rules with Inline Comments

我建议添加// eslint-disable-next-line而不是 file-wide eslint-disable

以下是Dan Abramov 的更多背景信息

有什么方法可以专门针对使用扩展运算符的地方禁用此规则?

// eslint-disable-next-line react-hooks/exhaustive-deps如果你认为你知道你在做什么,你总是可以的。


推荐阅读