0

I notice that inside class ExampleComponent extends React.Component {...} there are different ways of defining methods, with the former being a declaration for methods that is part of React and the latter being expressions for your own methods. Why is this? Why aren't they both in the same format?

  componentDidMount() {
    ...
  }

vs.

  myMethod = () => {
    ...
  }
stackjlei
  • 9,485
  • 18
  • 65
  • 113
  • because... they both do the same thing? one just happens to be an arrow function. It may or may not need to be, depending on how it is called. – Kevin B Jun 20 '17 at 20:43
  • @KevinB No, they're not the same? – Bergi Jun 20 '17 at 20:44
  • One is a valid ES6 method definition, the other is not. [It's an experimental syntax](https://stackoverflow.com/questions/31362292/how-to-use-arrow-functions-public-class-fields-as-class-methods) and should better go inside the constructor. – Bergi Jun 20 '17 at 20:45

2 Answers2

1

This one goes to prototype

fnProto() {

}

This one is experimental and goes directly to instance having this always refering to the instance.

fnInstance = () => {}

Translating to ES5

class Cmp {
 fnProto() {
   console.log('goes to proto')
 }

  fnInstance = () => {
    console.log('goes to instance')
  }
}

Will be roughly equivalent to

function Cmp() {
   this.fnInstance = (function() {
      console.log('goes to instance')
   }).bind(this)
}

Cmp.prototype.fnProto = function() {
   console.log('goes to proto')
}
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
-1

When you have

componentDidMount() {
    ...
  }

it is a lifecycle function and this inside it is automatically bound by default to the React Component context.

However when you define your own function, this inside it will refer to the content of the function itself. However if you define it using an arrow function like

myMethod = () => {
    ...
  }

this keyword inside it will refer to the parent context which in this case is the React Component context.

Check this article on Arrow function

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • What does "automatically bound by default to the React Component context" mean? *"this inside it will refer to the content of the function itself."* What is the "content" of a function? `this` certainly does not refer to that. – Felix Kling Jun 20 '17 at 21:58
  • @FelixKling, I suppose you are experienced enough to understand that, `content` was a typo. – Shubham Khatri Jun 21 '17 at 05:54