![](/img/trans.png)
[英]Creating Dynamic Routes using 'getStaticPaths' and 'getStaticProps' in NextJS
[英]Using getStaticProps in Nextjs
我正在制作我的第一個 Nextjs 項目,它是一個使用 JSON 占位符 API 的簡單博客。 出於某種原因,我不斷收到我的道具帖子未定義的錯誤,有人可以幫助我嗎?
我嘗試 console.log() 我的帖子,但結果我一直未定義
代碼
import React from 'react'
import { GetStaticProps } from 'next'
import headerStyles from '../styles/header.module.css'
interface Post {
userId: number;
id: number;
title: string;
body: string;
}
interface IProps {
posts: Post[];
}
export const getStaticProps: GetStaticProps = async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/posts')
const posts = await res.json()
return {
props: {
posts,
}
}
}
const Header: React.FC = () => {
return (
<div className={headerStyles.container}>
<h1 className={headerStyles.heading}>My Blog</h1>
</div>
)
}
const Home: React.FC<IProps> = ({ posts }) => {
console.log(posts)
return (
<>
<Header />
{posts.map(post => (
<div key={post.id}>
<h1> {post.title} </h1>
<button>Go to post</button>
</div>
))}
</>
)
}
export default Home
在您的情況下,它僅在構建后才能工作,因此如果您需要在沒有它的情況下檢查某些內容,則必須使用 getInitialProps
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.