Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use arrow function in constructor of a react component?

This question is similar to When using React Is it preferable to use fat arrow functions or bind functions in constructor? but a little bit different. You can bind a function to this in the constructor, or just apply arrow function in constructor. Note that I can only use ES6 syntax in my project.

1.

class Test extends React.Component{
  constructor(props) {
    super(props);

    this.doSomeThing = this.doSomeThing.bind(this);
  }

  doSomething() {}
}

2.

class Test extends React.Component{
  constructor(props) {
    super(props);

    this.doSomeThing = () => {};
  }
}

What's the pros and cons of these two ways? Thanks.

like image 770
ycdesu Avatar asked Apr 25 '17 03:04

ycdesu


People also ask

Can arrow functions be used as constructors?

Arrow functions cannot be used as constructors and will throw an error when used with new .

Why we should not use arrow functions in React?

An arrow function doesn't have its own this value and the arguments object. Therefore, you should not use it as an event handler, a method of an object literal, a prototype method, or when you have a function that uses the arguments object.

Can we use arrow function in functional component?

Some other prevalent event handlers are onMouseDown, onClick, and onBlur. To define the function within the component, you can use an arrow function or class method.


1 Answers

Option 1 is generally more preferable for certain reasons.

class Test extends React.Component{
  constructor(props) {
    super(props);

    this.doSomeThing = this.doSomeThing.bind(this);
  }

  doSomething() {}
}

Prototype method is cleaner to extend. Child class can override or extend doSomething with

doSomething() {
  super.doSomething();
  ...
}

When instance property

this.doSomeThing = () => {};

or ES.next class field

doSomeThing = () => {}

are used instead, calling super.doSomething() is not possible, because the method wasn't defined on the prototype. Overriding it will result in assigning this.doSomeThing property twice, in parent and child constructors.

Prototype methods are also reachable for mixin techniques:

class Foo extends Bar {...}
Foo.prototype.doSomething = Test.prototype.doSomething;

Prototype methods are more testable. They can be spied, stubbed or mocked prior to class instantiation:

spyOn(Foo.prototype, 'doSomething').and.callThrough();

This allows to avoid race conditions in some cases.

like image 76
Estus Flask Avatar answered Sep 18 '22 05:09

Estus Flask