useHookAtTopLevel
¥Summary
-
规则生效日期:
v1.0.0¥Rule available since:
v1.0.0 -
诊断类别:
lint/correctness/useHookAtTopLevel¥Diagnostic Category:
lint/correctness/useHookAtTopLevel -
此规则没有修复方案。
¥This rule doesn’t have a fix.
-
此规则的默认严重级别为 error。
¥The default severity of this rule is error.
-
此规则属于以下域:
¥This rule belongs to the following domains:
-
来源:
¥Sources:
-
与
react-hooks/rules-of-hooks相同¥Same as
react-hooks/rules-of-hooks
-
¥How to configure
{ "linter": { "rules": { "correctness": { "useHookAtTopLevel": "error" } } }}¥Description
强制所有 React 钩子都从顶层组件函数调用。
¥Enforce that all React hooks are being called from the Top Level component functions.
此规则仅适用于 React 项目。
¥This rule should be used only in React projects.
要了解为什么需要这个,请参阅 https://react.nodejs.cn/docs/hooks-rules.html#only-call-hooks-at-the-top-level
¥To understand why this required see https://react.nodejs.cn/docs/hooks-rules.html#only-call-hooks-at-the-top-level
¥Examples
¥Invalid
function Component1({ a }) { if (a == 1) { useEffect(); }}code-block.js:3:9 lint/correctness/useHookAtTopLevel ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ This hook is being called conditionally, but all hooks must be called in the exact same order in every component render.
1 │ function Component1({ a }) {
2 │ if (a == 1) {
> 3 │ useEffect();
│ ^^^^^^^^^
4 │ }
5 │ }
ℹ For React to preserve state between calls, hooks needs to be called unconditionally and always in the same order.
ℹ See https://react.nodejs.cn/docs/hooks-rules.html#only-call-hooks-at-the-top-level
function Component1({ a }) { if (a != 1) { return; }
useEffect();}code-block.js:6:5 lint/correctness/useHookAtTopLevel ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ This hook is being called conditionally, but all hooks must be called in the exact same order in every component render.
4 │ }
5 │
> 6 │ useEffect();
│ ^^^^^^^^^
7 │ }
8 │
ℹ Hooks should not be called after an early return.
1 │ function Component1({ a }) {
> 2 │ if (a != 1) {
│
> 3 │ return;
│ ^^^^^^^
4 │ }
5 │
ℹ For React to preserve state between calls, hooks needs to be called unconditionally and always in the same order.
ℹ See https://react.nodejs.cn/docs/hooks-rules.html#only-call-hooks-at-the-top-level
¥Valid
function Component1() { useEffect();}¥Related links
Biome v2.1 中文网 - 粤ICP备13048890号