Skip to content
← Back to rules

react/no-direct-mutation-state 正确性

它做了什么

此规则禁止在 React 组件中直接修改 this.state

请注意,此规则仅适用于类组件,不适用于函数组件。对于现代的 React 代码库,此规则可能并不必要或无关紧要。

为什么这是不好的?

React 组件 绝不应 直接修改 this.state,因为后续调用 setState() 可能会覆盖你所做的修改。

应将 this.state 视为不可变对象。

示例

以下为错误代码示例:

jsx
var Hello = createReactClass({
  componentDidMount: function () {
    this.state.name = this.props.name.toUpperCase();
  },
  render: function () {
    return <div>Hello {this.state.name}</div>;
  },
});

class Hello extends React.Component {
  constructor(props) {
    super(props);

    doSomethingAsync(() => {
      this.state = "bad";
    });
  }
}

以下为正确代码示例:

jsx
var Hello = createReactClass({
  componentDidMount: function() {
    this.setState({
      name: this.props.name.toUpperCase();
    });
  },
  render: function() {
    return <div>Hello {this.state.name}</div>;
  }
});

class Hello extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      foo: 'bar',
    }
  }
}

如何使用

要通过配置文件或 CLI 启用此规则,可以使用:

json
{
  "plugins": ["react"],
  "rules": {
    "react/no-direct-mutation-state": "error"
  }
}
bash
oxlint --deny react/no-direct-mutation-state --react-plugin

参考资料