![](/img/trans.png)
[英]Custom hooks with dependency lists and eslint-plugin-react-hooks
[英]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
}
這對我有用:
$ npm i --save-dev eslint-plugin-react-hooks
{
"plugins": [
...
"react-hooks"
],
"rules": {
...
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn"
}
...
$ npm i --save-dev eslint-config-react-app
{
...
"extends": "react-app"
$ npm i --save-dev eslint-plugin-flowtype
$ npm i --save-dev eslint@^5.0.0
實際上,當我將您的函數粘貼到由 create-react-app 創建的 App.js 文件時,運行該應用程序時會出現預期錯誤。
也許你的函數不被認為是一個 React 組件(你的函數被認為是一個通用函數)。 確保你在作用域上有 React ( import React from "react";
)
你的 eslint 配置也對我不起作用,但這個配置:
"eslintConfig": {
"extends": "react-app"
}
我添加了以下依賴項: @typescript-eslint/eslint-plugin
和@typescript-eslint/parser
到package.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.