E
E
Evgeii2020-02-27 14:28:50
React
Evgeii, 2020-02-27 14:28:50

Why do we need a constructor in react?

Hello. Tell me in your own words or where can I read available for what constructor is needed in react? What will be the difference between these two entries with and without constructor if everything works the same way?

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      books: [
        { name: 'ades', year: 2011 },
        { name: 'lili', year: 2013 },
      ],
      title: 'Hello',
      show: false
    }
  }
}

class App extends Component {
    state = {
     books: [
        { name: 'ades', year: 2011 },
        { name: 'lili', year: 2013 },
      ],
      title: 'Hello',
      show: false
    }
  }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
KnightForce, 2020-02-27
@KnightForce

It is needed not in React, but in the class.
In this case, you can do both.

E
Egor Zhivagin, 2020-02-27
@Krasnodar_etc

A constructor is needed if you need to do something once the first time the component is called. For example, earlier in the constructor of react components, we made bindings of class methods to give them a context.
If you just need to declare a state, then calling the constructor is usually redundant.
This is in addition to what you already wrote about. I would advise you to read about the constructor in OOP in general, not to be limited to react components

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question