React hooks:如何在 "mount" useEffect 中访问道具而不抛出 linting 警告

React hooks: how to access props within "mount" useEffect & not throw linting warning

除非我记错了,否则这是有效代码:

useEffect(() => {
   if (prop1) {
      doSomething();
   }
}, []);

(prop1 是道具)。但是在 linting 时出现以下错误:

React Hook useEffect has a missing dependency: 'prop1'. Either include it or remove the dependency array.

(react-hooks/exhaustive-deps)

我不想将 prop1 作为依赖项传递,因为我会失去 "only run on mount" 行为。但是我需要访问 doSomething() 的道具。

有什么建议吗?

你可以在这里提出这个问题.. [ESLint] Feedback for 'exhaustive-deps' lint rule

虽然我觉得在这种情况下你应该添加一个 eslint "ignore" 评论,如果你确定你不希望在更新 [=10] 时影响 运行 =].

这里提出了一个放松警告的合法案例.. https://github.com/facebook/react/issues/14920#issuecomment-467896512

还要检查你使用的插件版本 运行ning.. https://github.com/facebook/react/issues/14920#issuecomment-468801699

试试这个代码

const usemount = ( functionToDoSomeThing, data ) => {
    useEffect( () => {
        functionToDoSomeThing( data );
    },[] );
};

usemount( console.log, props );

我定义了一个函数来做某事并将其传递给 hook

在示例中我使用 console.log 函数

写这个问题时 Hooks 是新的,所以也许你已经知道了,但如果你或其他人想知道:

React 认为因为你的效果使用了 prop1 的值,所以它 "depends" 在 prop1 上并且应该在它发生变化时重新 运行 。这就是 linter 抱怨它没有被列为依赖项的原因。

然而,因为您希望效果仅 运行 "on mount",所以您希望它使用 initial/first 渲染中的 prop1 的值,并且不再 运行即使 prop1 发生变化。这与数组列出效果所依赖的所有变量的概念想法不一致,而这正是 linter 所关注的。

React Hooks FAQ 中提到的解决方案是使用 useRef 来跟踪这是否是第一个渲染(已编辑):

const firstRenderRef = useRef(true)

useEffect(() => {
  if (firstRenderRef.current) {
    firstRenderRef.current = false
    doSomething(prop1)
  }
}, [prop1])

这个解决方案满足了 linter,特别是因为它遵循了在数组中列出效果的所有依赖项的想法。 ref 允许效果也依赖于一个变量来判断这是否是第一次渲染,但是当值改变时不会重新渲染。