Next.js getStaticProps未按预期工作:fetchData始终返回undefined
问题:Home组件中fetchData始终返回undefined
我正在开发一个以卡片形式展示动态更新反馈的网站,但Home函数中的fetchData变量始终返回undefined。
我的代码如下:
import UserCard from "../components/usercard" import type { InferGetStaticPropsType, GetStaticProps } from 'next' type FeedbackData = { feedbackId: number feedback: string playerName: string userId: number rating: number } export const getStaticProps: GetStaticProps<{fetchData: FeedbackData[]}> = async() => { const response = await fetch("http://localhost:3000/api/all") const fetchData = await response.json() return { props: { fetchData, }, }; } function Home({ fetchData }: InferGetStaticPropsType<typeof getStaticProps>) { fetchData = fetchData ?? [] return ( <div> <h1 className="text-4xl font-bold text-center my-8">Feedbacks</h1> <ul className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3 p-6"> {fetchData.map((data: FeedbackData) => ( <UserCard key={data.feedbackId} feedback={data.feedback} userId={data.userId} playerName={data.playerName} feedbackId={data.feedbackId} rating={data.rating} /> ))} </ul> </div> ) } export default Home;
API的JSON响应为:
[ { "id": "6496e2e77cc2d26e513ea75a", "feedbackId": 129942, "feedback": "Feedback Test", "playerName": "ItsTuna_YT", "userId": 3522406346, "rating": 10 }, { "id": "6496ea491749221e0d96cbd5", "feedbackId": 810122, "feedback": "Feedback Test", "playerName": "ItsTuna_YT", "userId": 3522406346, "rating": 10 }, { "id": "6496ea5c1749221e0d96cbd7", "feedbackId": 214093, "feedback": "Feedback Test", "playerName": "ItsTuna_YT", "userId": 3522406346, "rating": 10 } ]
解决办法
1. 处理静态生成的局限性
getStaticProps在构建阶段执行,数据一旦构建完成就固定。如果你的反馈数据需要动态更新,有两种方案:
- 改用
getServerSideProps,每次用户请求时都从API获取最新数据:
export const getServerSideProps = async () => { const response = await fetch("http://localhost:3000/api/all") if (!response.ok) { return { props: { fetchData: [] } } } const fetchData = await response.json() return { props: { fetchData } } }
- 保留
getStaticProps并启用增量静态再生,定期更新页面数据:
export const getStaticProps: GetStaticProps<{fetchData: FeedbackData[]}> = async() => { const response = await fetch("http://localhost:3000/api/all") if (!response.ok) { return { props: { fetchData: [] } } } const fetchData = await response.json() return { props: { fetchData }, revalidate: 60 // 每60秒重新生成页面 }; }
2. 增加API请求错误处理
当前代码未处理请求失败的情况,若API返回错误状态码,会导致fetchData未正确赋值。添加状态检查:
export const getStaticProps: GetStaticProps<{fetchData: FeedbackData[]}> = async() => { const response = await fetch("http://localhost:3000/api/all") if (!response.ok) { return { props: { fetchData: [] } } } const fetchData = await response.json() return { props: { fetchData } } }
3. 修正类型定义(可选)
API返回的字段包含id,但你的FeedbackData类型未定义,补充后避免类型警告:
type FeedbackData = { id: string feedbackId: number feedback: string playerName: string userId: number rating: number }
4. 验证本地API可用性
确保http://localhost:3000/api/all可正常访问,返回状态码200和正确的JSON数组。可以直接在浏览器中打开该URL测试。
内容的提问来源于stack exchange,提问作者Tuna On Air
相关产品推荐
相关产品推荐

