Tuesday, 13 November 2018

reactjs - What is the difference between using constructor vs getInitialState in React / React Native?



I've seen both used interchangeably.



What are the main use cases for both? Are there advantages / disadvantages? Is one a better practice?


Answer






The two approaches are not interchangeable. You should initialize state in the constructor when using ES6 classes, and define the getInitialState method when using React.createClass.



See the official React doc on the subject of ES6 classes.



class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { /* initial state */ };

}
}


is equivalent to



var MyComponent = React.createClass({
getInitialState() {
return { /* initial state */ };
},

});

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...