为什么在有条件地使用react挂钩时eslint-plugin-react-hooks不警告?

jun*_*liu 7 reactjs eslint

我正在使用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"
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我在自定义钩子中有条件地使用钩子,则会出现这样的警告:“有条件地调用React Hook \“ useState \”。在每个组件渲染中必须以完全相同的顺序调用React Hooks。”

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

但是,如果我在函数组件中使用钩子,那将无法正常工作。

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

Dar*_*vic 12

这对我有用:

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


Mur*_*ruz 2

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

也许您的函数不被视为 React 组件(您的函数被视为通用函数)。确保你的范围内有 React ( import React from "react";)