![](/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.