react/hooks Suspicious
功能
运行 React Compiler 的 Rules of Hooks 验证:hooks 必须无条件调用,以一致的顺序调用,在组件或 hook 的顶层调用,并且不能作为一等值使用。
由 React Compiler 提供支持,该编译器每个文件运行一次,并与其他 React Compiler 规则共享。移植自 react-hooks/hooks。
此规则与 react/rules-of-hooks 存在重叠;因此上游将其禁用。
为什么这是不好的做法?
React 根据调用顺序跟踪 hook 状态。如果某个 hook 被有条件地调用,或者在不同渲染之间以不同顺序调用,就会破坏每次 hook 调用与其状态之间的关联,从而破坏组件状态。
示例
此规则的错误代码示例:
jsx
function Component(props) {
if (props.cond) {
useState(0); // hooks may not be called conditionally
}
return <div>{props.text}</div>;
}此规则的正确代码示例:
jsx
function Component(props) {
const [state, setState] = useState(0);
return <div onClick={() => setState(state + 1)}>{props.text}</div>;
}如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["react"],
"rules": {
"react/hooks": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["react"],
rules: {
"react/hooks": "error",
},
});bash
oxlint --deny react/hooks --react-plugin版本
此规则在 vnext 中添加。
