“react-hooks/rules-of-hooks”为什么不会抛出错误?

huangapple go评论64阅读模式
英文:

Why react-hooks/rules-of-hooks doesn't throw error?

问题

根据我的理解,hooks只能在自定义hooks或函数组件中使用。然而,即使下面的代码片段已经安装了react-hooks/rules-of-hooks规则,但在ClaimMonitorStore中使用useAlias,它并不是一个函数组件,似乎并没有引发任何错误。你能解释为什么在这种情况下没有抛出异常吗?

export const ClaimMonitorStore = (unifiedOnboardingStatus: TUnifiedOnboardingStatusStore) => ({
    claimMonitorsStatus: RenderingStatus.Ready,
    claimMonitorsErrMsg: "",
    searchText: "",
    alias: useAlias(),
})
英文:

From my understanding, hooks can only be used within custom hooks or functional components. However, even though the below code snippet has the react-hooks/rules-of-hooks installed, using useAlias inside the ClaimMonitorStore, which is not a functional component, doesn't seem to cause any errors. Can you explain why no exception is thrown in this case?

export const ClaimMonitorStore = (unifiedOnboardingStatus: TUnifiedOnboardingStatusStore) => ({
    claimMonitorsStatus: RenderingStatus.Ready,
    claimMonitorsErrMsg: "",
    searchText: "",
    alias: useAlias(),
})

答案1

得分: 1

因为 ESLint 规则无法区分普通函数和"React组件"。我在这里引用组件,因为(函数式)组件只是一个函数。没有明显的方法来确定它是组件还是非组件的普通函数,所以规则只检查在函数内部使用钩子。

这也是因为你的函数以大写字母开头。将其改为小写以从 linting 错误中获得更多信息:

React Hook "useAlias" 在函数"claimMonitorStore"中被调用,该函数既不是React函数组件,也不是自定义React Hook函数。React组件的名称必须以大写字母开头。React Hook的名称必须以单词"use"开头。eslintreact-hooks/rules-of-hooks

英文:

It's because the ESLint rule can't distinguish between a vanilla function and a "React component". I quote component here because a (functional) component is just a function. There's not an obvious way to determine if it's a component or a non-component vanilla function, so the rule just checks for the use of hooks inside of functions.

It's also because your function starts with a capital letter. Change it to lowercase to gain more insight from the linting error:

> React Hook "useAlias" is called in function "claimMonitorStore" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use".eslintreact-hooks/rules-of-hooks

huangapple
  • 本文由 发表于 2023年6月6日 12:54:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76411537.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定