如何在 Next JS 项目中使用 Firebase Cloud FireStore 数据库。如何正确初始化?

How to use Firebase Cloud FireStore Database in a Next JS project. How to initialize it correctly?

在 firebase.js 文件上,我这样做:

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

const firebaseConfig = {
  apiKey: process.env.APIKEY,
  authDomain: process.env.AUTHDOMAIN,
  databaseURL: process.env.DATABASEURL,
  projectId: process.env.PROJECTID,
  storageBucket: process.env.STORAGEBUCKET,
  messagingSenderId: process.env.MESSAGINGSENDERID,
  appId: process.env.APPID,
  measurementId: process.env.MEASUREMENTID
};

export function firebaseDB() {
  // Initialize Firebase
  if (!firebase.apps.length) {
    firebase.initializeApp(firebaseConfig);
    // firebase.analytics();
  }
  return firebase;
}

然后,在 pages/index.js 上我使用 getInitialProps:

App.getInitialProps = async () => {
  const firebaseDatabase = await firebaseDB();
  const db = firebaseDatabase.firestore();

  let result;

  db.collection("users")
    .add({
      first: "Ada",
      last: "Lovelace",
      born: 1815
    })
    .then(function(docRef) {
      console.log("Document written with ID: ", docRef.id);
      result = { docs: docRef };
    })
    .catch(function(error) {
      console.error("Error adding document: ", error);
      result = { error: error };
    });

    return result
};

我假设由于异步性质,我返回未定义的结果变量并收到此错误:

"App.getInitialProps()" should resolve to an object. But found "undefined" instead.

所以,我对我的配置方式不满意...有人可以透露一些信息吗?

以下是我能想到的一些方法:

  1. 为其创建一个 HOC 并包装将使用它的页面组件。 (https://medium.com/@uvictor/simple-firebase-authentication-with-next-js-using-hoc-higher-order-components-8e8931d25cfa)

  2. 在 Root 组件中初始化它,并将 DB ref 传递给子组件。例如,在你的 Root 组件中,你在那里声明你的路由。你想要做的是将 DB ref 传递给它下面的每个组件。虽然当你想做 SSR 时这可能会有问题。不确定结果如何。

  3. 如果只有一个页面将使用 Firebase(发生在我身上几次),就像你现在正在做的那样。

  4. 如果您正在考虑使用 Redux,您可能需要初始化 firebase 并将其绑定到商店 (https://github.com/prescottprue/react-redux-firebase)

我的建议是,尽量不要过于复杂。做对你有用的事。