Skip to content
← Back to rules

react/purity 正确性

功能

通过检查组件和 Hook 是否在渲染期间调用了已知的非纯函数(例如 Math.random()Date.now()performance.now()),验证组件和 Hook 是否为纯函数。

此规则由 React Compiler 提供支持,React Compiler 每个文件只运行一次,并与其他 React Compiler 规则共享。移植自 react-hooks/purity

为什么这很糟糕?

非纯渲染会针对相同的 props 和 state 返回不同的输出,从而破坏记忆化、并发渲染和可重放性。

示例

此规则的错误代码示例:

jsx
function Component() {
  const rand = Math.random();
  return <div>{rand}</div>;
}

此规则的正确代码示例:

jsx
import { useState } from "react";
function Component() {
  const [rand, setRand] = useState(0);
  return <button onClick={() => setRand(Math.random())}>{rand}</button>;
}

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "plugins": ["react"],
  "rules": {
    "react/purity": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  plugins: ["react"],
  rules: {
    "react/purity": "error",
  },
});
bash
oxlint --deny react/purity --react-plugin

版本

此规则已在 vnext 中添加。

参考