NextJS 15버전 Dynamic Routes

현채은·2024년 12월 24일

NextJS 15

목록 보기
1/1

NextJS 라우팅

동적 경로

동적경로 적용법
동적 세그먼트는 폴더 이름을 대괄호로 묶어서 만들 수 있습니다 [folderName].
예를 들어, [id]또는 [slug].

  • params 사용시 동기적으로 받아오니 TypeScript가 params라는 속성의 타입이 예상한 것과 다르다오류 발생
Type error: Type 'Props' does not satisfy the constraint 'PageProps'.
  Types of property 'params' are incompatible.
    Type '{ slug: string; }' is missing the following properties from type 'Promise<any>': then, catch, finally, [Symbol.toStringTag]

error Command failed with exit code 1.
  • 15 버전에서는 비동기(async/await)로 받아와야함

📄 공식문서

버전 14 및 이전 버전에서는 params동기식 prop이었습니다. 이전 버전과의 호환성을 위해 Next.js 15에서도 동기식으로 액세스할 수 있지만 이 동작은 향후 더 이상 지원되지 않습니다.

🚨 오류 발생 코드

import React from 'react';
// 15 ver에서는 type 지정시 Promise로 감싸야함 
type Props = {
  params:{
    slug: string; 
  }
}

export default async function PantsPage({ params }: Props) {
  return (
    <div>
      {params.slug} Page
    </div>
  );
}

💡 오류 해결 코드

  • 비동기로 Params값 받아오기
  • type 지정시 Promise 객체로 지정 → await를 사용하여 받아올 수 있음
import React from 'react';
// 15 ver에서는 type 지정시 Promise로 감싸야함 
type Props = {
  params:
  Promise<{ slug: string; }>
}
// 동적 라우팅 -> 빌드시 페이지를 미리 만들어 둘 수 없음
// 빌드시 미리 페이지 제작 주문 : generateStaticParams
export default async function PantsPage({ params }: Props) {
  // 15 ver에서는 비동기로 받아와야함
  const { slug } = await params
  return (
    <div>
      {slug} Page
    </div>
  );
}

export function generateStaticParams() {
  const products = ['pants', 'skirt'];
  return products.map(product => ({
    slug: product
  }))
}
profile
개발 기록 공간

0개의 댓글