我正在使用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
这对我有用:
$ npm i --save-dev eslint-plugin-react-hooks
Run Code Online (Sandbox Code Playgroud)
{
"plugins": [
...
"react-hooks"
],
"rules": {
...
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn"
}
...
Run Code Online (Sandbox Code Playgroud)
$ npm i --save-dev eslint-config-react-app
Run Code Online (Sandbox Code Playgroud)
{
...
"extends": "react-app"
Run Code Online (Sandbox Code Playgroud)
$ npm i --save-dev eslint-plugin-flowtype
Run Code Online (Sandbox Code Playgroud)
$ npm i --save-dev eslint@^5.0.0
Run Code Online (Sandbox Code Playgroud)
实际上,当我将您的函数粘贴到 create-react-app 创建的 App.js 文件上时,运行应用程序时会出现预期的错误。
也许您的函数不被视为 React 组件(您的函数被视为通用函数)。确保你的范围内有 React ( import React from "react";)
| 归档时间: |
|
| 查看次数: |
1018 次 |
| 最近记录: |