刚刚和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 Hello {
constructor() {
this.hello = "Hello";
this.returnString = this.returnString.bind(this);
}
returnString() {
return this.hello;
}
}
const { returnString } = new Hello();
console.log(returnString());
希望它能帮助未来的读者:)