简体   繁体   中英

Why I should use Constructor and Super functions for using Props?

When I use this.props without any constructor and super , it works well. So my question is why someone use this code:

  constructor(props) {
    super(props);
  }

You can completely skip the constructor if you don't have anything to initialize. But if you need to initialize something ( for example, state )then you need to use the constructor

constructor(props){
   super(props);
   this.state = {
      comments:[],
      selectedComment : null
    };

In the above code, we are using the constructor to initialize the state variables comment and selectedComment. Since you are extending your class from React.Component, you always have to call super in your constructor otherwise you will get an error.

By using an alternative class syntax, you can leave out the constructor and initialize the state as class field declaration

state = {
  comments:[],
  selectedComment : null
};

If you follow the above approach, there is no need to use the constructor function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM