react/no-did-mount-set-state Correctness
作用
禁止在 componentDidMount 生命周期方法中使用 setState。
此规则与函数组件无关,因此对于现代 React 代码库可以考虑将其禁用。
为什么这不好?
组件挂载后更新状态会触发第二次 render() 调用,并可能导致属性/布局抖动。 这会引发性能问题和非预期行为。
示例
以下是此规则的错误代码示例:
jsx
var Hello = createReactClass({
componentDidMount: function () {
this.setState({
name: this.props.name.toUpperCase(),
});
},
render: function () {
return <div>Hello {this.state.name}</div>;
},
});以下是此规则的正确代码示例:
jsx
var Hello = createReactClass({
componentDidMount: function () {
this.onMount(function callback(newName) {
this.setState({
name: newName,
});
});
},
render: function () {
return <div>Hello {this.state.name}</div>;
},
});配置
此规则接受以下字符串值之一:
"allowed"
允许在 componentDidMount 内部的嵌套函数中调用 setState,这是默认行为。
"disallow-in-func"
设置后,也会禁止在 componentDidMount 内部的嵌套函数中调用 setState。
如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["react"],
"rules": {
"react/no-did-mount-set-state": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["react"],
rules: {
"react/no-did-mount-set-state": "error",
},
});bash
oxlint --deny react/no-did-mount-set-state --react-plugin版本
此规则是在 v1.36.0 中添加的。
