The initial state of a React class component should be set to an object or null
- REACT_BAD_INITIAL_STATE_TYPE
- Error
- Medium
- react
This rule applies when the initial state of a React component defined as a class is not object or null
.
Because the state of a class component must be an object, React outputs a warning message if you assign a non-object value except null
as the initial state in the class constructor.
Noncompliant Code Example
View with compliant examples side by sideimport React from 'react';
export class Hello extends React.Component {
constructor(props) {
super(props);
this.state = "World"; // REACT_BAD_INITIAL_STATE_TYPE alarm because the type of state is string.
}
render() {
return <h1>Hello, {this.state}!</h1>;
}
}
Compliant Code Example
View with noncompliant examples side by sideimport React from 'react';
export class Hello extends React.Component {
constructor(props) {
super(props);
this.state = { name: "World" };
}
render() {
return <h1>Hello, {this.state.name}!</h1>;
}
}
Version
This rule was introduced in DeepScan 1.6.0-beta.
See
React Warning: Hello.state: must be set to an object or null