解构 function/method 会破坏 Firestore 中的东西 - 如何?
Destructuring a function/method breaks things in Firestore - How?
刚刚开始使用 Firestore,一切正常。我有这个片段:
this.db.collection('settings').onSnapshot(snapshot => {
snapshot.forEach(doc => {
this.cachedSettings[doc.id] = doc.data();
});
});
但是我一销毁数据,一切都崩溃了。对正在发生的事情感到有点困惑。我认为它与 this
绑定有关。
this.db.collection('settings').onSnapshot(snapshot => {
snapshot.forEach(({ id, data }) => {
this.cachedSettings[id] = data();
});
});
如果有人有任何参考,那也没关系。我找不到一个,因为我不知道这个问题的正确措辞。干杯
啊,找到罪魁祸首了。这是由于 JavaScript 中 this
的性质。考虑这个例子:
class Hello {
constructor() {
this.hello = "Hello";
}
returnString() {
return this.hello;
}
}
const { returnString } = new Hello();
console.log(returnString());
这将记录 undefined
。为什么? - 因为这里的 this
在解构时指的是函数 returnString
本身,因此 undefined
.
但是,这会起作用:
console.log(new Hello().returnString())
为了让第一个代码段起作用,我们需要将 returnString
绑定到 class,如下所示:
class Hello {
constructor() {
this.hello = "Hello";
this.returnString = this.returnString.bind(this);
}
returnString() {
return this.hello;
}
}
const { returnString } = new Hello();
console.log(returnString());
希望对未来的读者有所帮助:)
刚刚开始使用 Firestore,一切正常。我有这个片段:
this.db.collection('settings').onSnapshot(snapshot => {
snapshot.forEach(doc => {
this.cachedSettings[doc.id] = doc.data();
});
});
但是我一销毁数据,一切都崩溃了。对正在发生的事情感到有点困惑。我认为它与 this
绑定有关。
this.db.collection('settings').onSnapshot(snapshot => {
snapshot.forEach(({ id, data }) => {
this.cachedSettings[id] = data();
});
});
如果有人有任何参考,那也没关系。我找不到一个,因为我不知道这个问题的正确措辞。干杯
啊,找到罪魁祸首了。这是由于 JavaScript 中 this
的性质。考虑这个例子:
class Hello {
constructor() {
this.hello = "Hello";
}
returnString() {
return this.hello;
}
}
const { returnString } = new Hello();
console.log(returnString());
这将记录 undefined
。为什么? - 因为这里的 this
在解构时指的是函数 returnString
本身,因此 undefined
.
但是,这会起作用:
console.log(new Hello().returnString())
为了让第一个代码段起作用,我们需要将 returnString
绑定到 class,如下所示:
class Hello {
constructor() {
this.hello = "Hello";
this.returnString = this.returnString.bind(this);
}
returnString() {
return this.hello;
}
}
const { returnString } = new Hello();
console.log(returnString());
希望对未来的读者有所帮助:)