解构函数/方法会破坏Firestore中的内容 - 如何?

问题描述 投票:0回答:1

刚刚和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 google-cloud-firestore es6-class destructuring
1个回答
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());

希望它能帮助未来的读者:)

© www.soinside.com 2019 - 2024. All rights reserved.