ESLint VSCode插件在钩子方面没有产生警告

4

我使用 npx create-react-app my-app 创建了一个React应用,并运行了 yarn install 命令。接下来在 App.js 文件中添加以下代码:

const a = () => 1,
  b = () => 2,
  c = () => 3;

function App() {
  const wut = useMemo(() => {
    return { a: a(), b: b(), c: c() };
  }, [a]);
  useEffect(() => {
    console.log(a(), b(), c());
  }, [a]);

运行 yarn start 会给我警告,但 vscode 没有。

我添加了一个 .eslintrc.js 文件,其内容如下:

module.exports = {
  env: {
    browser: true,
    es6: true
  },
  extends: ["eslint:recommended", "plugin:react/recommended"],
  globals: {
    Atomics: "readonly",
    SharedArrayBuffer: "readonly"
  },
  parserOptions: {
    ecmaFeatures: {
      jsx: true
    },
    ecmaVersion: 2018,
    sourceType: "module"
  },
  plugins: ["react"],
  rules: {
    "react/prop-types": [0],
    "no-console": [0],
    "react-hooks/exhaustive-deps": "warn"
  }
};
3个回答

6
react/recommended规则列表中不包含react-hooks/exhaustive-deps

你可能没有安装eslint-plugin-react-hooks

注释如下:

注意:如果您使用的是Create React App,请等待相应版本的react-scripts发布,该版本将包含此规则,而无需直接添加它。

你正在使用哪个版本的c-r-a?理论上通过此PR添加了这个规则。


谢谢你的回答。我用yarn让它工作了,但是vscode给了我一个错误:Definition for rule 'react-hooks/exhaustive-deps' was not found。我卸载并重新安装了ESLint插件,并运行了yarn add eslint-plugin-react-hooks --dev,但问题仍然存在。 - HMR
你的VS Code设置运行ESLint如何?例如,(更或者少数事实上)插件有一个eslint.lintTask.options设置--你可能需要将其指向它知道如何读取的内容。不知道它是否会读取具有这样导出的JS文件。 - Dave Newton
通过更改 .eslintlintrc.js 文件中的 plugins: ["react", "react-hooks"] 解决了这个问题。同时,没有 .eslintrc.js 也可以正常工作。 - HMR

2
如果我在一个干净的create-react-app中有以下代码:
function App(props) {
  const {a,b,c}=props;
  const wut = useMemo(() => {
    console.log("this should not happen multiple times");
    return { a: a(), b: b(), c: c() };
  }, [a]);
  useEffect(() => {
    console.log(a(), b(), c());
  }, [a]);

然后,如果我删除.eslintrc.js文件,会出现React Hook useMemo has missing dependencies:警告,并有自动修复选项。
当我在项目根目录中有.eslintrc.js文件时,会出现错误Definition for rule 'react-hooks/exhaustive-deps' was not found.,这是因为缺少一个插件, plugins: ["react", "react-hooks"]解决了这个问题。
然而; 现在该规则默认处于关闭状态,因此不会发出警告,需要在.eslintrc.js中显式添加规则并将其设置为警告(或错误)。
  rules: {
    "react-hooks/exhaustive-deps": "error"
  }

当您添加 eslintrc.js 时,它会覆盖默认配置。 - Dennis Vash
@DennisVash 我明白,我不明白的是没有 eslintrc 它会发出警告(因此默认情况下也会发出警告)。使用未指定钩子规则处理方式的 eslintrc 将不会发出警告(表明默认值已更改)。 - HMR
当覆盖默认值为“没有规则”时,则需要指定您想要的任何内容。 - Dennis Vash
请注意,有覆盖规则,所有内容都在CRA网站上有记录。 - Dennis Vash
@DennisVash 我没有为 no-unused-vars 指定规则,但它会发出警告,因此默认情况下是开启的。但是,当没有 eslintrc 时,exhaustive-deps 规则是开启的(因此默认情况下是开启的),但是当存在 eslintrc 且没有为 exhaustive-deps 指定值时,该规则是关闭的(因此默认情况下是关闭的)。 - HMR

2

我正在使用TypeScript,所以对于我来说,答案是在我的VSCode设置中添加以下内容:

  "eslint.validate": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact"
  ],

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接