【问题标题】:react native and firebase - firebase function as referencereact native 和 firebase - firebase 函数作为参考
【发布时间】:2017-02-19 19:33:32
【问题描述】:

有人能解释一下为什么这段代码有效吗:

this.firebaseRef.on('value', (snapshot) => {//...});

这不是:

const foo = this.firebaseRef.on;
foo('value', (snapshot) => {//...});

?

在 react-native devtools 调试器中会抛出错误:Cannot read property 'Y' of undefined

这很有趣,因为当我设置断点并检查它时

foo === this.firebaseRef.on

它给了我真实的感觉。 typeof foo 是一个函数。我不明白。 once 也是如此。

【问题讨论】:

    标签: javascript firebase react-native firebase-realtime-database


    【解决方案1】:

    不同之处在于调用onthis 的值。当函数作为对象的成员调用时,this 将绑定到该对象。 (MDN) 当函数值作为独立变量调用时,this 绑定到全局对象或在严格模式下绑定到undefined。 (MDN)

    为了解决问题,您必须将函数bind 设置为正确的this 值。

    const foo = this.firebaseRef.on.bind(this.firebaseRef);
    foo('value', (snapshot) => {
      // ...
    });
    

    【讨论】:

      猜你喜欢
      • 2018-09-13
      • 2023-02-26
      • 1970-01-01
      • 2015-08-13
      • 2016-09-26
      • 2018-05-16
      • 2019-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多