我尝试在nextjs上使用getStaticprops从firestore读取数据,但是得到的却是一个空页面。我已经阅读了关于如何使用getStaticprops提取数据的文档,但是由于某种原因,它不起作用。这是我的代码的样子
import React from 'react'
import { db } from '../firebase'
import { collection, getDocs } from "firebase/firestore";
const reference = collection(db, "students");
export const getStaticProps = async () => {
const data = await getDocs(reference);
const students = data.docs.map(doc => ({...doc.data(), id: doc.id}));
return {
props: {
students
}
}
}
function Card({students = []}) {
return (
<div>
<p>This is just a test</p>
{students.map(student => (
<h1>{student.surname}</h1>
))}
</div>
)
}
export default Card
我哪里做错了?
2条答案
按热度按时间4nkexdtk1#
经过一些分析和尝试示例代码,这里是我的理解.
getStaticProps
仅用于静态站点生成。即,如果您的页面总是呈现相同的数据(您从API获得),则可以使用getStaticProps。例如,在您的案例中,您使用静态属性定义了Card组件。此组件将具有一个路由,例如
/Card
。当您运行
next build
时,数据将从服务器获取并用于该页面。然后npm start
。当您访问/Card
路由时,此数据将可用。(注意:getStaticProps将仅在生成时调用)但是如果你从其他页面调用相同的组件,那么静态的 prop 就不会被认为是你自己提供的 prop 了
如果您希望在页面呈现时获取学生数据,则在useEffect()中调用API。
x0fgdtte2#
在firebase文档示例中,(https://firebase.google.com/docs/firestore/query-data/获取-数据#web-version-9_6)
响应被用作数组(data.forEach),但在代码中,你像访问对象(data.docs)一样访问它。
你能试试这个吗,