react/no-will-update-set-state 正确性
作用
禁止在 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>;
},
});配置
此规则接受以下字符串值之一:
type: "允许" | "在函数中禁用"
How to Use
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 中添加的。
