0

I have some question that is about using ES6 class in react.

The question is as follows.

About creating component in react,

I am using this way.

class A extends Component{
    constructor(){
        this.state = {
            'blah' : 123
        }
    }
}

but i saw other way.

class A extends Component{
    state = {
        'blah' : 123
    }    
}

question 1)

what is difference between first way and second way?

question 2)

In the environment I built,

The second method generates an error.

how to use second way? (directly defining state)

Mamun
  • 66,969
  • 9
  • 47
  • 59
김기현
  • 41
  • 1
  • 1
    They are equivalent. The second one is currently a proposal for extending the language with that syntax. You need to configure your build tool to understand this syntax. – Felix Kling May 14 '18 at 06:07
  • check it out https://stackoverflow.com/a/37788410/7750289 – CodeZombie May 14 '18 at 06:14

1 Answers1

1

Question1 : There is no difference in first and second way both can be used to initializing state.

Question2 : You can use second approach in the react version 16 or above. It is not supported in old version. For old version you still need to use approach 1 that is constructor approach.

I hope it helps you.

R.K.Saini
  • 2,678
  • 1
  • 18
  • 25