跳至內容

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

此規則預設為啟用。

作用

限制程式碼開發者不能直接更改 this.state 的值

為什麼這不好?

之後呼叫 setState() 可能會覆蓋您所做的變更

範例

jsx
 // error
 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';
     });
   }
 }

 // success
 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',
     }
   }
 }

參考資料

以 MIT 授權釋出。