【问题标题】:Why is the data stored in firestore not being fetched in react?为什么存储在firestore中的数据没有在react中获取?
【发布时间】:2020-09-23 13:05:36
【问题描述】:

我正在尝试从 firestore 获取数据进行反应,但我在控制台中得到以下信息(无数据):

t {vf: e, m_: t, xf: null, $f: false, kf: false, …} $f: 假 T_:空 kf: 假的 m_: t {路径: n} vf: e {uf: n, hf: e, lf: FirebaseAppImpl, _f: e, INTERNAL: {…}, …} xf: 空 存在:(...) ID: (...) 元数据:(...) 参考:(...) 原型:对象

我的 Firebase 设置

import firebase from "firebase";

const firebaseConfig = firebase.initializeApp({
  apiKey: "AIzaSyDTpOEQVLZFezpUNDMPmh0FckcQmDQp_rQ",
  authDomain: "ecommerce-app-f6a42.firebaseapp.com",
  databaseURL: "https://ecommerce-app-f6a42.firebaseio.com",
  projectId: "ecommerce-app-f6a42",
  storageBucket: "ecommerce-app-f6a42.appspot.com",
  messagingSenderId: "455019623318",
  appId: "1:455019623318:web:2d90e3539b53ed939663b7",
  measurementId: "G-BJGR6HPE48",
});

const db = firebaseConfig.firestore();

export default db;

使用 db 从 firestore 获取数据并对其进行安慰:

import db from './firebase';

componentDidMount() {
    db.collection("Products").onSnapshot((snap) => console.log(snap));
  }

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore


    【解决方案1】:

    数据被提取得很好。您正在记录一个内容被混淆的对象。

    snap 是一个QuerySnapshot 类型的对象。您应该使用它,如您在链接的 API 文档中看到的那样。我还建议阅读主要产品documentation,了解如何处理查询结果的示例。至少,您应该迭代该 QuerySnapshot 中包含的 DocumentSnapshot 对象,并考虑在每个对象中记录文档数据。

    这是来自documentation 的示例:

    db.collection("cities").where("state", "==", "CA")
        .onSnapshot(function(querySnapshot) {
            var cities = [];
            querySnapshot.forEach(function(doc) {
                cities.push(doc.data().name);
            });
            console.log("Current cities in CA: ", cities.join(", "));
        });
    

    这是另一个使用更简单的get() 操作而不是实时侦听器:

    db.collection("cities").where("capital", "==", true)
        .get()
        .then(function(querySnapshot) {
            querySnapshot.forEach(function(doc) {
                // doc.data() is never undefined for query doc snapshots
                console.log(doc.id, " => ", doc.data());
            });
        })
        .catch(function(error) {
            console.log("Error getting documents: ", error);
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 2021-08-14
      相关资源
      最近更新 更多