Initialization of the state of reacting components

I came across some code defining the state of a component inside a class, for example:

// Snippet 1 class Sample extends React.Component { state = { count: 0 } } 

The way I learned React was to declare a state inside the class constructor:

 // Snippet 2 class Sample extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } } 

The only difference I can think of is that state initialization in the constructor guarantees the correct state initialization in the component life cycle.

What is the difference between two pieces of code? In fragment 1, is it possible to assume that the state should be correctly set when the class is initialized?

+5
source share
2 answers

What you are looking for is ES7+ Property Initializers . This is because Facebook knows that Javascript will change in the future. They want to be able to cope with these changes.

According to facebook ES7 + Property Initializers

Wait, assigning properties seems to be a very imperative way of defining classes! You are right, however, we designed it that way because it is idiomatic. We fully expect a more declarative syntax for initializing properties in order to arrive in a future version of JavaScript ....

Here is the Facebook link. Also in more detail here.

also offer link

+3
source

It's just syntactic sugar to make the class look cleaner already on babel: https://babeljs.io/docs/plugins/transform-class-properties/

0
source

Source: https://habr.com/ru/post/1261234/


All Articles