[Next.js] getStaticProps 구현
본문 바로가기
프레임워크/Next.js

[Next.js] getStaticProps 구현

by 은돌1113 2022. 2. 20.

getStaticProps 구현

1️⃣ 주어진 id로 게시물을 렌더링 하기 위해서는 필요한 데이터를 가져와야 합니다.

그러려면 lib/posts.js를 다시 열고 getPostData 아래에 다음 기능을 추가합니다.

(id를 기반으로 데이터를 반환합니다.)

export function getPostData(id) {
  const fullPath = path.join(postsDirectory, `${id}.md`)
  const fileContents = fs.readFileSync(fullPath, 'utf8')

  // Use gray-matter to parse the post metadata section
  const matterResult = matter(fileContents)

  // Combine the data with the id
  return {
    id,
    ...matterResult.data
  }
}

 

2️⃣ pages/posts/[id].js를 다음과 같이 바꿉니다.

import { getAllPostIds } from '../../lib/posts'
import { getAllPostIds, getPostData } from '../../lib/posts'

export async function getStaticProps({ params }) {
  const postData = getPostData(params.id)
  return {
    props: {
      postData
    }
  }
}

게시물 페이지는 이제 getStaticProps에서 getPostData() 함수를 사용하여 게시물 데이터를 가져와 반환합니다.

 

3️⃣ pages/posts/[id].js에서 postData로 return 한 데이터를 가지고 Post의 구성 요소를 다음과 같이 수정합니다.

export default function Post({ postData }) {
  return (
    <Layout>
      {postData.title}
      <br />
      {postData.id}
      <br />
      {postData.date}
    </Layout>
  )
}

 

4️⃣ yarn dev 또는 npm run dev로 개발 서버를 구동하고

아래 페이지를 방문 해보면 아래와 같이 외부에서 받아온 데이터로 출력되는 걸 볼 수 있습니다.

 

🥕 localhost:3000/posts/ssg-ssr

🥕 localhost:3000/posts/pre-rendering

 

이를 요약하자면 다음과 같습니다.


🤨 만약 오류가 발생한다면 파일에 코드가 올바른 지 확인 해보세요!

 

🥕 pages/posts/[id]. js가 다음과 같아야 합니다.

 

GitHub - vercel/next-learn: Learn Next.js Starter Code

Learn Next.js Starter Code. Contribute to vercel/next-learn development by creating an account on GitHub.

github.com

 

🥕 lib/posts/js가 다음과 같이 보여야 합니다.

 

GitHub - vercel/next-learn: Learn Next.js Starter Code

Learn Next.js Starter Code. Contribute to vercel/next-learn development by creating an account on GitHub.

github.com

 

🥕 여전히 동작하지 않는다면 아래 깃허브를 참고하세요.

 

GitHub - vercel/next-learn: Learn Next.js Starter Code

Learn Next.js Starter Code. Contribute to vercel/next-learn development by creating an account on GitHub.

github.com


 

Learn | Next.js

Production grade React applications that scale. The world’s leading companies use Next.js by Vercel to build pre-rendered applications, static websites, and more.

nextjs.org

 

'프레임워크 > Next.js' 카테고리의 다른 글

[Next.js] Post 페이지 다듬기  (0) 2022.02.20
[Next.js] Render MarkDown  (0) 2022.02.20
[Next.js] getStaticPaths 구현  (0) 2022.02.20
[Next.js] 동적 경로  (0) 2022.02.20
[Next.js] 요청 시 데이터 가져오기  (0) 2022.02.18

댓글