繁体   English   中英

为什么 eslint-plugin-react-hooks 在有条件地使用 React 钩子时不会发出警告?

[英]Why eslint-plugin-react-hooks doesn't warn when using react hooks conditionally?

我正在使用 react 16.8 和 eslint-plugin-react-hooks 1.6.0 。当我有条件地使用钩子时,我希望 eslint 会警告我。 这是我的配置:

"eslintConfig": {
    "parser": "babel-eslint",
    "plugins": [
      "react-hooks"
    ],
    "rules": {
      "react-hooks/rules-of-hooks": "error",
      "react-hooks/exhaustive-deps": "warn"
    }
}

如果我在自定义钩子中有条件地使用钩子,将会有这样的警告:“React Hook \\"useState\\" is called conditionally. React Hooks must be in the完全相同的顺序在每个组件渲染中调用。“

function useCustomHook() {
  if (Math.random() > 0.5){
    const [a, setA] = useState(0)
  }
}

但是如果我在函数组件中使用钩子,它就不起作用。

function MyComponent() {
  if (Math.random() > 0.5){
    const [a, setA] = useState(0)
  }
  return null
}

这对我有用:

  1. 首先安装相应的 eslint 插件:
   $ npm i --save-dev eslint-plugin-react-hooks
  1. 将它与默认配置一起添加到您的 .eslintrc 中:
  {
    "plugins": [
      ...
      "react-hooks"
    ],
    "rules": {
      ...
      "react-hooks/rules-of-hooks": "error",
      "react-hooks/exhaustive-deps": "warn"
    }
    ...
  1. 安装 eslint 配置模板“react-app”:
  $ npm i --save-dev eslint-config-react-app
  1. 在您的 .eslintrc 中从新安装的配置扩展:
  {
    ...
    "extends": "react-app"
  1. 确保您拥有新包的正确对等依赖项,例如我必须执行以下操作:
  $ npm i --save-dev eslint-plugin-flowtype
  1. 确保你的 eslint 包是 5+ 版本,例如 5.16.0 工作,更高的也应该工作(但要注意更高的 eslint 也需要更新的 nodejs)。
  $ npm i --save-dev eslint@^5.0.0
  1. 重启 VSCode
  2. 按 Cmd-Shift-U 打开输出终端,在下拉菜单中切换到 Eslint 并检查它是否加载没有错误。

实际上,当我将您的函数粘贴到由 create-react-app 创建的 App.js 文件时,运行该应用程序时会出现预期错误。

也许你的函数不被认为是一个 React 组件(你的函数被认为是一个通用函数)。 确保你在作用域上有 React ( import React from "react"; )

你的 eslint 配置也对我不起作用,但这个配置:

"eslintConfig": {
  "extends": "react-app"
}

我添加了以下依赖项: @typescript-eslint/eslint-plugin@typescript-eslint/parserpackage.json并将以下内容添加到.eslintrc.js

extends: [... 'plugin:@typescript-eslint/recommended', 'plugin:react-hooks/recommended']
parser: '@typescript-eslint/parser',
plugins: [..., '@typescript-eslint'],

你不应该在条件范围内使用钩子。 这将导致错误,因为反应知道如何将有状态值与变量关联的唯一方法是按顺序,在这种情况下将不一致。

看看文档,他们拼出了钩子的规则。 https://reactjs.org/docs/hooks-rules.html

你想要的是更像这样的东西

 const [a, setA] = useState(initialVal)
 if (Math.random() > 0.5){
    setA(0)
 }

暂无
暂无

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

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