State initialization should be in a constructor
9import { convertData } from '../../utilities/convertData';
10
11export class Watch extends Component {
12 state = {13 data: null,14 }15
16 componentDidMount() {
17 const yourId = this.props.match.params.id;
State initialization should be in a constructor
6import { url } from '../../API/makeRequest';
7
8class Home extends Component {
9 state = {10 data: null,11 }12
13 componentDidMount() {
14 fetch(url)
Description
This issue is based on the organizational behavior pattern as developers prefer many things differently, e.g., vim over emacs or emacs over vim.
There are two styles to initialize state in React component class:
- Inside the constructor of the class (Recommended)
- As a class property
It can be fixed by using the alternate approach to the issue raised:
- When the state is initialized inside the constructor, it can be fixed by initializing the state as a class property
- When the state is initialized as a class property, it can be fixed by initializing inside the constructor
Bad Practice
class Foo extends React.Component {
state = { bar: 0 }
render() {
return <div>Foo</div>
}
}
Recommended
class Foo extends React.Component {
constructor(props) {
super(props)
this.state = { bar: 0 }
}
render() {
return <div>Foo</div>
}
}