When using React Is it preferable to use fat arrow

2019-06-18 04:28发布

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?

2条回答
smile是对你的礼貌
2楼-- · 2019-06-18 04:55

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.

查看更多
登录 后发表回答