【问题标题】:getInitialProps() should resolve to an object. But found "undefined" insteadgetInitialProps() 应该解析为一个对象。但发现“未定义”
【发布时间】:2023-03-14 17:55:02
【问题描述】:

我正在尝试使用 getInitialProps 从 firebase 获取数据到我的 next.js 应用程序,但数据显示在 VS Code 终端中(以及一些错误)。但是,在浏览器中,我收到此消息

请检查代码

// Other import code
import { firestore } from "../firebase/firebase.utils";

const Hotels = (props) => {
  return (
    // jsx code
  );
};

Hotels.getInitialProps = async (ctx) => {
  let hotelsRef = firestore.collection("hotels");
  let query = hotelsRef
    .get()
    .then((snapshot) => {
      if (snapshot.empty) {
        console.log("No matching documents.");
        return;
      }

      snapshot.forEach((doc) => {
        console.log(doc.id, "=>", doc.data());
        return { props: doc.data() };
      });
    })
    .catch((err) => {
      console.log("Error getting documents", err);
    });
};

export default Hotels;

感谢任何帮助。

【问题讨论】:

    标签: reactjs firebase next.js


    【解决方案1】:

    我认为你应该从 getInitialProps 的对象返回,但在你的情况下,你没有返回任何东西,也没有使用 async await

    给你:

    Hotels.getInitialProps = async (ctx) => {
        let hotelsRef = firestore.collection("hotels");
        let snapshot = await hotelsRef.get()
        if (snapshot.empty) {
            console.log("No matching documents.");
            return;
        }
        let data = []
        snapshot.forEach((doc) => {
            console.log(doc.id, "=>", doc.data());
            data.push(doc.data());
        });
        return { props : data };
    };
    
    

    【讨论】:

    • 现在我收到错误消息“snapshot.map 不是函数”,所以我使用了 forEach 但在 VS Code 终端中返回 { props: undefined }(chrome 控制台中的空数组)。
    • 所以快照不是数组,请检查它的值并返回它,我刚刚根据您的代码将其转换为,所以您的主要问题已解决,请接受并支持答案。
    • 我不再在数组中获得任何值。它是空的。
    • 清理了 sn-p - 有一个额外的 {
    • 我只在我的 vs 代码控制台而不是在道具中得到结果。你知道为什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 2016-01-29
    相关资源
    最近更新 更多