[英]When using React Is it preferable to use fat arrow functions or bind functions in constructor?
创建 React 类时,哪个更可取?
export default class Foo extends React.Component {
constructor (props) {
super(props)
this.doSomething = this.doSomething.bind(this)
}
doSomething () { ... }
}
或者
export default class Foo extends React.Component {
doSomething = () => { ... }
}
我的一个同事认为后者会导致内存问题,因为 babel 将代码转换为在闭包中捕获this
,并且该引用将导致实例无法被 GC 清理。
对此有何想法?
公共类字段语法(所以doSomething = () => {...}
)还不是 ECMAScript 的一部分,但它做得很好,我非常有信心它会到达那里。
所以使用这种语法迫使你转译,但它带来了好处:
this
绑定的清晰、简洁的语法对我来说,这是一场明显的胜利。 在大多数情况下,您甚至不需要constructor(props)
,从而使您免于那个样板super
调用。
如果 Babel 实现会导致内存泄漏,您可以确定这些问题会被快速找到并修复。 由于必须编写更多代码,您更有可能自己造成泄漏。
渲染函数中的绑定会导致在每次渲染时创建新函数,这意味着差异算法认为存在变化。 当您在构造函数中绑定时,这不会发生。
在这里你可以看到在构造函数中使用箭头绑定和绑定的编译差异: https : //babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Creact%2Cstage-2&experimental=true&loose=false&spec=false&code =class%20x%20extends%20React.Component%20%7B%0A%20%20constructor%20(props)%20%7B%0A%20%20%20%20super(props)%3B%0A%20%20 %20%20%0A%20%20%20%20this.onChange%20%3D%20this.onChange.bind(this)%3B%0A%20%20%7D%0A%20%20%0A%20% 20onChange%20()%20%7B%20console.log(%27change%20x%27)%3B%20%7D%0A%7D%0A%0Aclass%20y%20extends%20React.Component%20%7B%0A% 20%20onChange%20%3D%20()%20%3D%3E%20%7B%20console.log(%27change%20y%27)%3B%20%7D%0A%7D
这里的链接清楚地强调了“在构造函数中绑定方法”而不是使用箭头函数作为实现事件绑定的短代码是安全的。
这是链接: https : //reactjs.org/docs/react-without-es6.html#autobinding供参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.