react/no-set-state 风格
它的作用
禁止在 React 组件中使用 this.setState。
为什么这是不好的?
当使用将应用状态与 UI 组件分离的架构时(例如 Flux),可能希望禁止使用组件的本地状态。此规则在只读应用程序(不使用表单)中尤其有用,因为在这些情况下通常不需要本地组件状态。
示例
此规则的错误代码示例:
jsx
var Hello = createReactClass({
getInitialState: function () {
return {
name: this.props.name,
};
},
handleClick: function () {
// 禁止使用 this.setState
this.setState({
name: this.props.name.toUpperCase(),
});
},
render: function () {
return <div onClick={this.handleClick.bind(this)}>Hello {this.state.name}</div>;
},
});如何使用
通过配置文件或命令行启用此规则,可以使用:
json
{
"plugins": ["react"],
"rules": {
"react/no-set-state": "error"
}
}bash
oxlint --deny react/no-set-state --react-plugin