react/no-redundant-should-component-update Style
作用
当继承 React.PureComponent 时,禁止使用 shouldComponentUpdate。
请注意,使用 PureComponent在现代 React 中不推荐。
为什么这不好?
React.PureComponent 会自动实现 shouldComponentUpdate,并对 props 和 state 进行浅比较。 在继承 React.PureComponent 的类中定义 shouldComponentUpdate 是多余的,并且违背了使用 React.PureComponent 的目的。如果你需要自定义比较逻辑,请改为继承 React.Component。
示例
以下是此规则的错误代码示例:
jsx
class Foo extends React.PureComponent {
shouldComponentUpdate() {
// 执行检查
}
render() {
return <div>Radical!</div>;
}
}
function Bar() {
return class Baz extends React.PureComponent {
shouldComponentUpdate() {
// 执行检查
}
render() {
return <div>Groovy!</div>;
}
};
}以下是此规则的正确代码示例:
jsx
class Foo extends React.Component {
shouldComponentUpdate() {
// 执行检查
}
render() {
return <div>Radical!</div>;
}
}
function Bar() {
return class Baz extends React.Component {
shouldComponentUpdate() {
// 执行检查
}
render() {
return <div>Groovy!</div>;
}
};
}
class Qux extends React.PureComponent {
render() {
return <div>Tubular!</div>;
}
}如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["react"],
"rules": {
"react/no-redundant-should-component-update": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["react"],
rules: {
"react/no-redundant-should-component-update": "error",
},
});bash
oxlint --deny react/no-redundant-should-component-update --react-plugin版本
此规则于 v1.33.0 中添加。
