首页 > 解决方案 > 通过传递一个空数组作为第二个参数,使用“useEffect”钩子只运行一次代码,但是 ESLint 抱怨空数组

问题描述

我正在 Visual Studio Code IDE 上开发一个 react-native 项目。

出于某种原因,我的 Visual Studio Code 开始自动填充代码以解决 lint 错误。

例如,我使用useEffecthook 只运行一次代码(所以我需要传递一个空数组作为 的第二个参数useEffect)。代码如下:

useEffect(() => {
     ...
      // imaging my code here has 'foo', 'bar', etc variables
     ...
     ...
    return () => {
      console.log('Screen did unmount');
    };
  }, []); // ESLint complains the empty array.

ESLint 在我输入上面的代码后立即抱怨空数组:

React Hook useEffect has missing dependencies: 'foo', 'bar'. Either include them or remove the dependency array.eslint(react-hooks/exhaustive-deps)

如果我现在 ctrl+s 来保存我的代码。Visual Studio 自动将代码添加到空数组中:

useEffect(() => {
     ...
      // imaging my code here has 'foo', 'bar', etc variables
     ...
     ...
    return () => {
      console.log('Screen did unmount');
    };
  }, [foo, bar]); 

我的两个问题:

  1. 根据useEffect钩子的工作方式,为了只运行一次代码,我必须传递一个空数组。为什么 ESLint 会抱怨这个?useEffect如果不推荐我的代码,那么让代码只运行一次的正确方法是什么?

  2. 如何让我的 Visual Studio Code 停止自动添加代码来解决 ESLint 错误?

标签: react-nativevisual-studio-code

解决方案


我为此建议了两种方法。

您可以// eslint-disable-next-line在您的代码中使用

useEffect(() => {
    ...
    // imaging my code here has 'foo', 'bar', etc variables
    ...
    ...
    return () => {
        console.log('Screen did unmount');
    };
    // eslint-disable-next-line
}, [])

或者您可以删除编辑 Visual Studio 代码的 eslint 设置。

Visual Studio 设置

干杯。


推荐阅读