此問題與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