无法使用React获取Firebase集合 [英] Can't fetch firebase collection with React

查看:40
本文介绍了无法使用React获取Firebase集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React hooks + firebase.

I'm using React hooks + firebase.

在firebase中,我创建了一个名为项目"的集合

In firebase, I created a collection called "projects"

当我尝试使用以下命令控制台记录数据时:

When I try to console log the data with:

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

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

我得到以下对象:

应该看不到我的数据吗?

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

Below are my firebase and context set up

firebase.js

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

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

推荐答案

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

The key of how you interact with Firestore in your code seems to be:

firebase.db.collection("projects")

此代码在Firestore中创建对 projects 集合的引用.它不会从数据库中检索任何数据.

This code creates a reference to the projects collection in Firestore. It does not retrieve any data from the database yet.

要获取数据,您需要将一个侦听器附加到该集合.来自有关从集合中获取文档的Firestore文档:

To get data, you need to attach a listener to the collection. From the 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);
    });

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

You'll need to do something similar in your code.

通常在React项目中,您可以通过在 then()回调中调用 setState(...)来以组件状态存储数据,然后进行渲染JSX中状态的内容.

Typically in React projects, you'll store the data in the component's state by calling setState(...) in the then() callback, and then render the content from the state in your JSX.

这篇关于无法使用React获取Firebase集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆