[Next.js] Url 객체를 사용한 라우팅

2020. 12. 26. 00:54카테고리 없음

Next.js의 라우팅을 Url object를 사용하여 페이지 이동시 예상한대로 작동하지 않았다고 합니다.

 

stackoverflow.com/q/64172527/5570106

 

Unexpected behaviour when use Next.js router push with URL object

According to the Next.js documentation, I can use the router push function with a URL object to route dynamic paths, like this example : import { useRouter } from 'next/router' export default func...

stackoverflow.com

답변으로 다음과 같이 달았습니다.

stackoverflow.com/a/65449450/5570106

 

Unexpected behaviour when use Next.js router push with URL object

According to the Next.js documentation, I can use the router push function with a URL object to route dynamic paths, like this example : import { useRouter } from 'next/router' export default func...

stackoverflow.com

Url object로 부터 경로 생성시 query라는 이름 때문에 url 쿼리 형태인 ?key=value 형태로 달리는 것으로 생각한 것 같았습니다.

 

컴포넌트의 사용방법과 그에 따른 결과를 예시로 들었습니다.

 

컴포넌트가 아래와 같은 형식이고 컴포넌트에 전달된 포스트의 값이 {id: 123}일 경우 라우터가 생성하는 경로는 [pid]의 값이 대체되어 http://localhost:3000/post/123 입니다.

import { useRouter } from 'next/router'
...
const router = useRouter()
...
router.push({ pathname: '/post/[pid]', query: { pid: post.id }, })