我试图创建一个网站,显示动态更新反馈卡。我的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条答案
按热度按时间8xiog9wr1#
您的代码似乎缺少
getStaticPaths
。您需要它来告诉Nextjs使用getStaticProps
渲染哪些页面。除非您不使用动态路由。如果一个页面有Dynamic Routes并使用getStaticProps,它需要定义一个静态生成的路径列表。
来源:https://nextjs.org/docs/pages/building-your-application/data-fetching/get-static-paths