我可以在反应组件的构造函数中使用箭头函数吗? [英] Can I use arrow function in constructor of a react component?

查看:525
本文介绍了我可以在反应组件的构造函数中使用箭头函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题类似于使用React时最好在构造函数中使用胖箭头函数或绑定函数,但有点不同。您可以在构造函数中将函数绑定到,或者在构造函数中应用箭头函数。请注意,我只能在我的项目中使用ES6语法。

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.

推荐答案

选项1通常因某些原因更为可取。

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();
  ...
}

当实例属性

this.doSomeThing = () => {};

或ES.next类字段

or ES.next class field

doSomeThing = () => {}

代替,调用 super.doSomething()是不可能的,因为原型上没有定义方法。覆盖它将导致在父和子构造函数中分配 this.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.

原型方法也是可达到mixin技术:

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.

这篇关于我可以在反应组件的构造函数中使用箭头函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆