Assignment should not be made to this.state
in the React component's specific methods
- REACT_DIRECT_ASSIGN_TO_STATE
- Error
- Medium
- react
This rule applies when assignment is made to this.state
in the React component's specific methods.
When updating this.state
inside the following methods, you should use setState()
:
- DOM event handler
componentDidMount()
componentDidUpdate()
shouldComponentUpdate()
componentWillMount()
componentWillReceiveProps()
componentDidCatch()
UNSAFE_componentWillMount()
UNSAFE_componentWillReceiveProps()
If this.state
is modified directly inside the above methods, it may cause a problem because the component is not re-rendered or the updated state is no applied.
Noncompliant Code Example
View with compliant examples side by sideimport React from 'react';
export class SayHello extends React.Component {
constructor(props) {
super(props);
this.handleChanged = this.handleChanged.bind(this);
}
handleChanged() {
this.state = { message: "Hello" }; // REACT_DIRECT_ASSIGN_TO_STATE alarm
alert(this.state.message);
}
render() {
return (
<button onClick={this.handleChanged}>Click!</button>
);
}
}
Compliant Code Example
View with noncompliant examples side by sideimport React from 'react';
export class SayHello extends React.Component {
constructor(props) {
super(props);
this.handleChanged = this.handleChanged.bind(this);
}
handleChanged() {
this.setState({ message: "Hello" });
alert(this.state.message);
}
render() {
return (
<button onClick={this.handleChanged}>Click!</button>
);
}
}
Version
This rule was introduced in DeepScan 1.2.0-alpha.