export const getServerSideProps: GetServerSideProps = async () => {
const ref = collection(db, "books");
const results = [];
const unsub = onSnapshot(ref, (snapshot) => {
snapshot.forEach((doc) => {
results.push({ ...doc.data(), id: doc.id });
});
//here i get the results
console.log(results)
});
// here is empty
console.log(results)
return {
props: {
books: results,
},
};
};我试图从getServerSideProps函数的firestore数据库中获取实时数据,在快照中,我可以得到结果,但是当它在数组之外时,它是空的,我不能传递给道具。
发布于 2022-01-06 06:09:06
我不使用onSnapshot,而是使用getDocs (您需要从‘firebase/firestore’导入):
export const getServerSideProps: GetServerSideProps = async () => {
const [results, setResults] = useState([]);
const ref = collection(db, 'books');
const snapshot = await getDoc(docRef);
articlesSnapshot.forEach((doc) => {
setResults((oldArray) => [...oldArray, doc.data()]);
});
return {
props: {
books: results,
},
};
};发布于 2022-09-11 09:25:16
我也遇到了同样的问题。在这里,我们应该使用get()而不是快照,因为接下来我们将处理幕后更新的数据。
所以像这样重写你的代码
export async function getServerSideProps(context) {
const resultref = await db.collection("books").get();
const results = resultRef.docs.map((doc)=>({
id: doc.id,
resultData: doc.data()
}))
return {
props: { books: JSON.parse(JSON.stringify(results)) },
}
}因此map函数将返回变量结果中的新数组,然后将其作为支持进行深度复制和传递。
我希望这能给你带来预期的结果。
https://stackoverflow.com/questions/70552803
复制相似问题