【问题标题】:No eslint warning when ref is missing in useEffect dependency在 useEffect 依赖项中缺少 ref 时没有 eslint 警告
【发布时间】:2020-05-28 14:38:17
【问题描述】:

我对@9​​87654322@ 中的ref 有一点怀疑。 我需要将其添加到依赖项中吗?

const App = () => {
  const ref = useRef();
  useEffect(() => {
    //do something about ref
  }, []); //<-- ref is not here
}

上面的代码没有给出任何 eslint 警告。 ref 是否在依赖项中豁免?

【问题讨论】:

  • ref 本身是引用稳定的,它指向ref.current 的值是变化的。

标签: reactjs react-hooks ref use-effect


【解决方案1】:

简短的回答是肯定的,您不必将 ref 添加到依赖项数组中。

要更深入地了解,您可以阅读 Dan Abramov 的 A Complete Guide to useEffect。从那里引用,回答你的问题:

(您可以从 deps 中省略 dispatch、setState 和 useRef 容器值,因为 React 保证它们是静态的。但指定它们也没有坏处。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-13
    • 2020-11-21
    • 2020-05-06
    • 1970-01-01
    • 2022-04-04
    • 2021-05-14
    • 2021-12-07
    • 2021-01-14
    相关资源
    最近更新 更多