【问题标题】:SSR getServerSideProps NextJS with Firebase/FirestoreSSR getServerSideProps NextJS 与 Firebase/Firestore
【发布时间】:2021-09-25 23:31:00
【问题描述】:

希望大家有一个美好的一天!这周我开始学习更多关于 nextJS 的知识,今天,我被这个叫做 SSR 的东西卡住了,我知道为什么但是当我通过道具时它总是返回未定义,似乎它甚至没有填充,但是当我尝试到console.log,数据在那里

这是我的code

export async function getServerSideProps({ query }) {
  // Fetch data from external API
  try {
    console.log("HEI WE ARE HERE");
    console.log(query.pid);
    const ref = firebase
      .firestore()
      .collection("mycollection")
      .doc(query.pid)
      .get()
      .then((querySnapshot) => {
        const dataX = [];
        if (querySnapshot.exists) {
          dataX.push(querySnapshot.data());
        }
        console.log("CEK DATAX: " + JSON.stringify(dataX));
      })
      .catch((e) => {
        alert(err);
      });
    // Pass data to the page via props
    return { props: { dataX } };
  } catch (err) {
    return { props: {} };
  }
}

这是我的function Page() 看起来像

export default function Page({ dataX }) {
  const router = useRouter();
  console.log("CEK PAGE DATAX: " + JSON.stringify(dataX));

如果您在我的 function Page() 上看到,在 console.log 中,这是我浏览器中的结果 [![screentshoot1][1]][1]

控制台结果在我的getServerSideProps 看起来像这样 [![screentshoot2][2]][2]

如您所见,在我的getServerSideProps 中,我的dataX 不是空的,但是当通过时,它变得未定义:(

有人请帮忙.. [1]:https://i.stack.imgur.com/d8ply.png [2]:https://i.stack.imgur.com/Fy5ZB.png

【问题讨论】:

    标签: firebase next.js server-side-rendering


    【解决方案1】:

    我认为问题在于,在下面的部分中,变量dataX 是在Promise 回调中定义的,但是您在外部范围中使用了它。您应该在.then(() => {}) 回调中返回dataX,最后执行return { props: { dataX: ref } }; 而不是return { props: { dataX } };

    const ref = firebase
        .firestore()
        .collection("mycollection")
        .doc(query.pid)
        .get()
        .then((querySnapshot) => {
            const dataX = [];
            if (querySnapshot.exists) {
                dataX.push(querySnapshot.data());
            }
            console.log("CEK DATAX: " + JSON.stringify(dataX));
        })
        .catch((e) => {
            alert(err);
        });
    // Pass data to the page via props
    return { props: { dataX } };
    

    【讨论】:

    • 嘿,谢谢你的回答,我已经尝试过你的建议,please see this image,但我得到了新的错误,看起来像这样Reason: object ("[object Promise]") cannot be serialized as JSON. Please only return JSON serializable data types.
    • 哦,是的,你应该这样做 const ref = await firebase... 以便你得到一个正确的 JSON 对象而不是 Promise 或类似的东西。
    猜你喜欢
    • 2022-10-18
    • 2021-08-10
    • 2021-07-15
    • 2022-12-01
    • 2019-08-02
    • 2020-06-30
    • 2022-12-03
    • 2018-07-28
    • 2020-07-25
    相关资源
    最近更新 更多