react/no-direct-mutation-state 정확성
동작 방식
이 규칙은 리액트 컴포넌트 내에서 this.state를 직접 수정하는 것을 금지합니다.
이 규칙은 클래스 컴포넌트에만 적용되며, 함수 컴포넌트에는 적용되지 않습니다. 현대적인 리액트 코드베이스에서는 이 규칙이 필요하거나 관련이 없을 수 있습니다.
왜 문제가 되는가?
리액트 컴포넌트는 절대 this.state를 직접 변경해서는 안 됩니다. 이후 setState()를 호출하면, 여러분이 수행한 변경 사항이 덮어쓰일 수 있기 때문입니다.
this.state는 불변이라고 여겨져야 합니다.
예시
이 규칙에 적합하지 않은 코드 예시:
jsx
var Hello = createReactClass({
componentDidMount: function () {
this.state.name = this.props.name.toUpperCase();
},
render: function () {
return <div>안녕하세요 {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>안녕하세요 {this.state.name}</div>;
}
});
class Hello extends React.Component {
constructor(props) {
super(props)
this.state = {
foo: 'bar',
}
}
}사용 방법
구성 파일 또는 명령줄 인터페이스에서 이 규칙을 활성화하려면 다음을 사용할 수 있습니다:
json
{
"plugins": ["react"],
"rules": {
"react/no-direct-mutation-state": "error"
}
}bash
oxlint --deny react/no-direct-mutation-state --react-plugin