SSR getServerSideProps NextJS with Firebase/Firestore



希望大家度过美好的一天!本周,我开始了解更多关于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));

如果你在console.log中的function Page()上看到,这是我浏览器中的结果[![屏幕截图1][1][1]

我的getServerSideProps中的控制台结果如下[![屏幕截图2][2]][2]

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

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

我认为问题在于,在下面的部分中,变量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 } };

最新更新