此问题与When using React Is it preferable to use fat arrow functions or bind functions in constructor?类似,但略有不同。您可以在构造函数中将函数绑定到this
,或者只需在构造函数中应用箭头函数。请注意,我只能在我的项目中使用ES6语法。我可以在反应组件的构造函数中使用箭头函数吗?
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 =() => {};
}
}
什么是这两种方式的利弊?谢谢。
感谢您的回复!这个答案帮了我很多。你能否解释更多关于'在某些情况下的竞争状况'?谢谢。 – ycavatars
例如,如果您想模拟doSomething或测试它被调用,但是在您有机会窥探/存储实例之前调用它。如果在构造函数或代码中的其他地方调用doSomething(当它是框架钩子等)时,可能会发生这种情况。 – estus
真的非常感谢您的解答。这有助于我找到潜在的错误,谢谢。 – ycavatars