簡體   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