简体   繁体   English

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

[英]use 'useEffect' hook to run code only once by passing an empty array as the 2nd parameter, however ESLint complains the empty array

I am developing a react-native project on Visual Studio Code IDE.我正在 Visual Studio Code IDE 上开发 react-native 项目。

For some reason, my Visual Studio Code starts to automatically fill code to solve lint errors.出于某种原因,我的 Visual Studio Code 开始自动填充代码以解决 lint 错误。

For example, I use useEffect hook to run some code only once (so I need to pass an empty array as the 2nd parameter of useEffect ).例如,我使用useEffect钩子只运行一次代码(所以我需要传递一个空数组作为useEffect的第二个参数)。 Code is like below:代码如下:

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

The ESLint complains that empty array like immediately after I typed above code: ESLint 在我输入上面的代码后立即抱怨空数组:

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

If I now ctrl+s to save my code.如果我现在 ctrl+s 来保存我的代码。 Visual Studio automatically adding code to the empty array: Visual Studio 自动将代码添加到空数组中:

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

My two questions:我的两个问题:

  1. According to the way how the useEffect hook works, in order to run the code only once, I have to pass an empty array.根据useEffect挂钩的工作方式,为了只运行一次代码,我必须传递一个空数组。 Why ESLint complains about that?为什么 ESLint 会抱怨这个? What is the right way to have the code inside useEffect to only run once if mine is not recommended?如果不推荐我的,那么让useEffect中的代码只运行一次的正确方法是什么?

  2. How to make my Visual Studio Code stop automatically adding code to resolve ESLint error?如何让我的 Visual Studio Code 停止自动添加代码来解决 ESLint 错误?

I suggest two methods for this.我为此建议了两种方法。

You can use // eslint-disable-next-line in your 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
}, [])

Or you can remove edit the settings of eslint of Visual Studio code.或者您可以删除编辑 Visual Studio 代码的 eslint 设置。

Visual Studio settings Visual Studio 设置

Cheers.干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM