在React中,不应该直接修改组件的状态(state)。因此,使用setState()方法来更新状态。
例如,下面的代码是错误的方式来更新state,会导致react/no-direct-mutation-state问题:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
handleClick() {
this.state.count += 1;
}
render() {
return (
{this.state.count}
);
}
}
正确的方式是使用setState()方法来更新状态:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
{this.state.count}
);
}
}
在上面的代码中,当用户点击按钮时,handleClick()方法调用setState()来更新组件的状态,而不是直接改变状态。这将解决react/no-direct-mutation-state问题。