【问题标题】:Can't fetch firebase collection with React无法使用 React 获取 firebase 集合
【发布时间】:2023-03-13 21:04:01
【问题描述】:

我正在使用 React hooks + firebase。

在 firebase 中,我创建了一个名为“projects”的集合

当我尝试使用控制台记录数据时:

const Dashboard = () => {
  const { firebase } = useContext(GlobalContext);

  return (
    <div className="container">
      {console.log(firebase.db.collection("projects"))}
    </div>
  );
};

我得到以下对象:

应该看不到我的数据吗?

以下是我的 firebase 和上下文设置

firebase.js

import app from "firebase/app";
import "firebase/auth";
import "firebase/firebase-firestore";

const config = {//mydata}

class Firebase {
  constructor() {
    app.initializeApp(config);
    this.auth = app.auth();
    this.db = app.firestore();
  }
}

export default new Firebase();

context.js

import React, { useReducer } from "react";
import { projectReducer } from "./reducers";
import firebase from "../components/firebase/firebase";

export const GlobalState = props => {
  const [projects, setProjects] = useReducer(projectReducer, []);

  return (
    <GlobalContext.Provider
      value={{
        projects,
        firebase
      }}
    >
      {props.children}
    </GlobalContext.Provider>
  );
};

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore react-hooks


    【解决方案1】:

    您如何在代码中与 Firestore 交互的关键似乎是:

    firebase.db.collection("projects")
    

    此代码在 Firestore 中创建对 projects 集合的引用。它确实没有从数据库中检索任何数据。

    要获取数据,您需要将侦听器附加到集合。来自Firestore documentation on getting documents from a collection

    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);
        });
    

    您需要在代码中执行类似的操作。

    通常在 React 项目中,您将通过在 then() 回调中调用 setState(...) 将数据存储在组件的状态中,然后在 JSX 中呈现状态中的内容。

    【讨论】:

      猜你喜欢
      • 2021-05-07
      • 1970-01-01
      • 2019-10-06
      • 2020-03-15
      • 2019-10-18
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      • 2017-05-15
      相关资源
      最近更新 更多