react/no-will-update-set-state Correctness
作用
禁止在 componentWillUpdate 生命周期方法中使用 setState。
为什么这不好?
在组件更新阶段更新状态可能会导致组件状态不确定,因此是不被允许的。 这可能会导致你的 React 应用出现意外行为和 bug。
示例
以下是此规则的错误代码示例:
jsx
var Hello = createReactClass({
componentWillUpdate: function () {
this.setState({
name: this.props.name.toUpperCase(),
});
},
render: function () {
return <div>Hello {this.state.name}</div>;
},
});以下是此规则的正确代码示例:
jsx
var Hello = createReactClass({
componentWillUpdate: function () {
this.props.prepareHandler();
},
render: function () {
return <div>Hello {this.state.name}</div>;
},
});配置
此规则接受以下字符串值之一:
"allowed"
禁止在函数之外的 componentWillUpdate 中调用任何 this.setState。
"disallow-in-func"
通过禁止即使在函数内部调用 `this.setState``,使此规则更加严格。
如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["react"],
"rules": {
"react/no-will-update-set-state": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["react"],
rules: {
"react/no-will-update-set-state": "error",
},
});bash
oxlint --deny react/no-will-update-set-state --react-plugin版本
此规则是在 v1.37.0 中添加的。
