인프런, 유데미/React로 트위터 만들기
next.js의 다이나믹 라우팅
5_hyun
2023. 2. 21. 21:29
반응형
다이나믹 라우팅
sns에서 게시글의 아이디를 활용하여 게시글을 불러오는 페이지를 만들려고 하면 next.js에서는 다이나믹 라우팅을 사용할 수 있다.
파일 구조
파일 구조는 이렇게 post 폴더 안에 [id].js를 하면된다.
코드
const router = useRouter();
const { id } = router.query;
useRouter를 이용하면 url에 뜨는 게시글의 id를 받아올 수 있다.
getServerSideProps에서 id 찾기
context.store.dispatch({
type: LOAD_POST_REQUEST,
// context.params.id 혹은 context.query.id라고 하면 useRouter에 똑같이 접근할 수 있다.
data: context.params.id,
});
위 코드는 getServerSideProps 안에서의 코드이며 context.params.id 혹은 context.query.id로 id를 얻어올 수 있다.
반응형