小编jun*_*liu的帖子

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

我正在使用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)

reactjs eslint

7
推荐指数
2
解决办法
1018
查看次数

标签 统计

eslint ×1

reactjs ×1