使用React是否最好在构造函数中使用胖箭头函数或绑定函数? [英] When using React Is it preferable to use fat arrow functions or bind functions in constructor?

查看:123
本文介绍了使用React是否最好在构造函数中使用胖箭头函数或绑定函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 导出默认类Foo扩展了React.Component {
构造函数(道具){
super(props)
this.doSomething = this.doSomething.bind(this)
}

doSomething(){...}
}

  export default class Foo extends React.Component {
doSomething =()=> {...}
}

我的同事认为后者会导致内存问题因为babel透过代码来捕获关闭中的这个,引用将导致实例不被GC清理。



任何关于这个的想法?

解决方案

公共类字段语法(so doSomething =( )=> {...} )是尚未成为ECMAScript的一部分但是它做得很好,我很有信心会到达那里。



所以使用这个语法强制你透明,但它带来了好处:




  • 清除,简洁的语法表达绑定

  • 浏览器支持这个

  • 不需要实现的未来证明



对我来说一个明显的胜利。在大多数情况下,您甚至不需要一个构造函数(props),可以从该样板超级调用中保存。



如果Babel实现会导致内存泄漏,那么您可以确定这些内容将被快速找到并修复。你更可能通过编写更多的代码来创建泄漏。


When creating a React class, which is preferable?

export default class Foo extends React.Component {
  constructor (props) {
    super(props)
    this.doSomething = this.doSomething.bind(this)
  }

  doSomething () { ... }
}

or

export default class Foo extends React.Component {
  doSomething = () => { ... }
}

A coworker of mine thinks that the latter causes memory problems because babel transpiles the code to capture this inside the closure, and that reference will cause the instance to not be cleaned by GC.

any thoughts about this?

解决方案

The public class field syntax (so doSomething = () => {...}) is not yet part of ECMAScript but it is doing well and I am pretty confident that it will get there.

So using this syntax forces you to transpile, but it brings advantages:

  • clear, concise syntax for expressing this binding
  • future proof for when browsers support this
  • not concerned with implementation

For me, this is a clear win. In most cases, you don't even need a constructor(props), saving you from that boilerplate super call.

If the Babel implementation would cause memory leaks, you can be sure those would have been found and fixed quickly. You are more likely to create leaks yourself by having to write more code.

这篇关于使用React是否最好在构造函数中使用胖箭头函数或绑定函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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