react/state-in-constructor Style
作用
强制 state 初始化风格只能是在 构造函数中,或作为类属性。
该规则与函数组件无关,因此对于现代 React 代码库来说,可以 考虑禁用。
为什么这不好?
不一致的 state 初始化风格会让代码库更难维护和理解。 此规则在 React 类组件中强制统一的模式。
示例
默认情况下,此规则在 "always" 模式下的错误代码示例:
jsx
class Foo extends React.Component {
state = { bar: 0 };
render() {
return <div>Foo</div>;
}
}默认情况下,此规则在 "always" 模式下的正确代码示例:
jsx
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = { bar: 0 };
}
render() {
return <div>Foo</div>;
}
}"never" 模式
将强制 state 初始化风格必须使用类属性。
此规则在 "never" 模式下的错误代码示例:
jsx
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = { bar: 0 };
}
render() {
return <div>Foo</div>;
}
}此规则在 "never" 模式下的正确代码示例:
jsx
class Foo extends React.Component {
state = { bar: 0 };
render() {
return <div>Foo</div>;
}
}配置
此规则接受以下字符串值之一:
"always"
强制在构造函数中初始化 state。 这是默认模式。
"never"
强制使用类属性初始化 state。
使用方法
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["react"],
"rules": {
"react/state-in-constructor": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["react"],
rules: {
"react/state-in-constructor": "error",
},
});bash
oxlint --deny react/state-in-constructor --react-plugin版本
此规则于 v1.26.0 中添加。
