简体   繁体   中英

How can I get `eslint-plugin-react-hooks` to lint functional components that are exported as `default`?

I have deliberately created a simple functional component that breaks the rules of hooks. It contains the following snippet.

  if (Math.rand > 0.5) {
    const [name, setName] = useState("fred");
  }

I expect that eslint-plugin-react-hooks would lint this clear mistake, but it doesn't. After trying to get to the bottom of this, I discovered that when I am exporting a function as default - the linter does not do it's thing. (I am using the @typescript-eslint/parser for what that's worth).

Is there any way to have the latter syntax work with eslint / eslint-plugin-react-hooks , or must I always create a named functional component, then run export default name; beneath the function?

https://codesandbox.io/s/hook-demo-c10y2

So... I just discovered that this is a known bug with eslint-plugin-react-hooks . Seems like you need to have a named function for the plugin to catch & lint your errors. https://github.com/facebook/react/issues/14404 (specifically just the "react-hooks/rules-of-hooks" rule).

Your code is breaking the rules of hooks at which a hook must only be called at the top level of your code. It cannot be placed inside an if...else statement. Check out the rules of hooks here: https://reactjs.org/docs/hooks-rules.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM