【问题标题】:How to fix 'Cannot set property 'ref' of undefined'?如何修复'无法设置未定义的属性'ref''?
【发布时间】:2019-04-04 16:58:06
【问题描述】:

所以我尝试做的很简单:从 Cloud Firestore 接收数据。

我有以下代码:

import React from 'react';
import firebase from "react-native-firebase";

export default class newsFeed extends React.Component {
 constructor() {
  this.ref = firebase.firestore().collection('keys')
}

 async load(id) {
  const doc = await this.ref.doc(id).get()
  if (doc.exists) {
    return doc.data()
  }
 }
}

我收到一个错误:'无法设置未定义的属性'ref'。

我该如何解决它,有什么问题?

从本教程中学到的:https://medium.com/react-native-training/firebase-sdk-with-firestore-for-react-native-apps-in-2018-aa89a67d6934

【问题讨论】:

  • 使用 Lamba 函数 ( => )。普通函数不继承 this 上下文。

标签: javascript firebase react-native google-cloud-firestore


【解决方案1】:

通常箭头函数有帮助。

 load = async (id) => { //...

【讨论】:

    【解决方案2】:

    您正在导出类而不创建实例。你应该这样做:

    import React from 'react';
    import firebase from "react-native-firebase";
    
    class NewsFeed extends React.Component {
     constructor() {
      this.ref = firebase.firestore().collection('keys')
    }
    
     async load(id) {
      const doc = await this.ref.doc(id).get()
      if (doc.exists) {
        return doc.data()
      }
     }
    }
    
    export default newsFeed = new NewsFeed();
    

    希望有帮助:)

    【讨论】:

      猜你喜欢
      • 2020-07-19
      • 2021-02-04
      • 2019-12-13
      • 2018-06-28
      • 1970-01-01
      • 1970-01-01
      • 2018-04-25
      • 2019-12-08
      • 2020-06-19
      相关资源
      最近更新 更多