只是与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();
});
});
如果有任何参考,也可以。我找不到一个人,因为我不知道该问题的正确措辞。干杯
答案 0 :(得分:0)
啊,找到了罪魁祸首。这是由于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 Hello {
constructor() {
this.hello = "Hello";
this.returnString = this.returnString.bind(this);
}
returnString() {
return this.hello;
}
}
const { returnString } = new Hello();
console.log(returnString());
希望它对未来的读者有所帮助:)