[英]How does React call the render function of an ES6 class in a such a way that `this` does not refer to the class itself?
例如,給定具有函數increaseQty的類
increaseQty() {
this.qty++
}
和電話
render() {
return (
<div>
<button onClick={this.increaseQty}>Increase</button>
</div>
)
}
this.qty是不確定的,除非我寫我的構造線結合的情況下this
在構造函數中的作用
constructor(props) {
super(props)
this.qty = 0
this.increaseQty = this.increaseQty.bind(this) // <---- like so
}
但是,如果您只是正常使用它,那么在正常的es6類中就不是這種情況:
https://jsfiddle.net/omrf0t20/2/
class Test {
constructor() {
this.qty = 0
}
increaseQty() {
console.log(++this.qty)
}
doStuff() {
this.increaseQty()
}
}
const t = new Test()
t.doStuff() // prints 1
哪些方面發生反應使得它使render
調用時沒有的情況下this
?
這里的區別是,在你的榜樣與之反應你逝去的increaseQty
作為回調到另一個組件,但在第二,你是在當前上下文中調用它。
您可以在簡化示例中看到差異
class Test {
constructor() {
this.qty = 0
}
increaseQty() {
console.log(++this.qty)
}
doStuff() {
this.increaseQty(); // no need to bind
}
listenClicks() {
// you should use bind to preserve context
document.body.addEventListener('click', this.increaseQty.bind(this));
}
}
React指南還建議您在構造函數中綁定方法,使代碼更加優化,綁定一次並始終使用相同的函數,而不是為每個render()
調用創建新的綁定版本。
這不是一個特定於ES6的問題(除了我們引用類和構造函數之外)。 你在函數中所做的只是遞增一個值。 如果該值尚未初始化為某些內容(即使在ES5中),則會引發錯誤。 您不能將1添加到undefined
。
在ES5(和ES6真的)這將是一個問題:
var myObj = {
addOne: function() {
this.qty++;
}
}
myObj.addOne(); // Error! this.qty is undefined
雖然這會解決它:
var myObj = {
qty: 0,
addOne: function() {
this.qty++;
}
}
myObj.addOne(); // Good to go
你班上的情況也是如此。 您不能將尚未聲明和初始化的變量增加到數值。
在一個更簡單的例子中:
var x;
x++;
會拋出一個錯誤,而這個:
var x = 0;
x++;
很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.