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