state without constructor
I have been using with ‘constructor’ and ‘super’, However, I happened to see following way below to declare local state of a component for the first time when I had a outsourcing project.
class FeedCommentList extends Component<Props, State> { state: State = { isLoading: true, number: 6 };...}
After the project, I figured out how these are different from each other briefly(There are more to dig out though…). Simple way to compare both is using babel ‘Try out’ feature.
I put both cases into Babel ‘Try out’ feature.
INPUT
1.Input on ‘Try out’ feature with ‘constructor’
class App extends React.Component {
constructor(props) {
super(props);
this.state = { lat: null, errorMessage: '' };
}
}
2.Input on ‘Try out’ feature
class App extends React.Component {
state = { lat: null, errorMessage: '' };
}
OUTPUT
1.Output from ‘Try out’ feature with ‘constructor’
class App extends React.Component {
constructor(props) {
super(props);
this.state = { lat: null, errorMessage: '' };
}
}
2.Output from ‘Try out’ feature
class App extends React.Component {
constructor(...args) {
var _temp;
return _temp = super(...args),
this.state = { lat: null, errorMessage: '' },
_temp;
}
}
Reference :
- https://reactjs.org/docs/react-component.html
- https://reactjs.org/docs/state-and-lifecycle.html
- https://itnext.io/how-to-properly-define-state-in-react-components-47544eb4c15d
- https://www.robinwieruch.de/react-state-without-constructor/
- Modern React with Redux by Stephen Grider
I am blogging what I’ve learned to find later here for myself. If you happened to read this shit and there is wrong information, it would be appreciated to add a comment below.