react/no-did-update-set-state 正确性
它的作用
禁止在 componentDidUpdate 中使用 setState。
为什么这不好?
在组件更新后再更新状态会触发第二次 render() 调用,并可能导致属性/布局抖动。
示例
以下是此规则的错误代码示例:
jsx
var Hello = createReactClass({
componentDidUpdate: function () {
this.setState({
name: this.props.name.toUpperCase(),
});
},
render: function () {
return <div>Hello {this.state.name}</div>;
},
});以下是此规则的正确代码示例:
jsx
var Hello = createReactClass({
componentDidUpdate: function () {
this.props.onUpdate();
},
render: function () {
return <div>Hello {this.props.name}</div>;
},
});jsx
var Hello = createReactClass({
componentDidUpdate: function () {
this.onUpdate(function callback(newName) {
this.setState({
name: newName,
});
});
},
render: function () {
return <div>Hello {this.props.name}</div>;
},
});配置
此规则接受以下字符串值之一:
类型:"allowed" | "disallow-in-func"
How to use
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["react"],
"rules": {
"react/no-did-update-set-state": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["react"],
rules: {
"react/no-did-update-set-state": "error",
},
});bash
oxlint --deny react/no-did-update-set-state --react-pluginVersion
This rule was added in v1.62.0.
