22.2.19 (토) +27days
Routing
https://nextjs.org/docs/routing/introduction
Next.js has a file-system based router built on the concept of pages.
When a file is added to the pages directory, it's automatically available as a route.
The files inside the pages directory can be used to define most common patterns.
Dynamic Routes
https://nextjs.org/docs/routing/dynamic-routes
Defining routes by using predefined paths is not always enough for complex applications. In Next.js you can add brackets to a page ([param]) to create a dynamic route (a.k.a. url slugs, pretty urls, and others).
[pid]로 다이나믹한 url을 생성할 수 있게 한다.
router.query로 key와 value를 꺼낼 수 있다.
catch all routes with [...slug] 하면 query의 key slug에 배열로 값들이 존재
optional catch all routes [[...slug]] slug 없는 경우도 대응 가능
Caveats(주의사항)
pages match 정적인게 먼저 매칭된다.
server side 코드 없이 빌드된 페이지에서 router.query는 처음에는 빈 객체다.
Imperatively
https://nextjs.org/docs/routing/imperatively
[next/link](<https://nextjs.org/docs/api-reference/next/link>) should be able to cover most of your routing needs, but you can also do client-side navigations without it, take a look at the documentation for next/router.
The following example shows how to do basic page navigations with [useRouter](<https://nextjs.org/docs/api-reference/next/router#userouter>):
next/link 없이 router에 직접 페이지를 푸시하는 방법
router.push(’/about’);
Shallow Routing
https://nextjs.org/docs/routing/shallow-routing
Shallow routing allows you to change the URL without running data fetching methods again, that includes [getServerSideProps](<https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props>), [getStaticProps](<https://nextjs.org/docs/basic-features/data-fetching/get-static-props>), and [getInitialProps](<https://nextjs.org/docs/api-reference/data-fetching/get-initial-props>).
You'll receive the updated pathname and the query via the [router object](https://nextjs.org/docs/api-reference/next/router#router-object) (added by [useRouter](<https://nextjs.org/docs/api-reference/next/router#userouter>) or [withRouter](<https://nextjs.org/docs/api-reference/next/router#withrouter>)), without losing state.
To enable shallow routing, set the shallow option to true. Consider the following example:
데이터 페칭없이 browser에 보이는 url만 변경
router.push(’/?coutner=10, undefined, {shallow: true}’);
다른 url에서 하면 page가 변경됨
API Routes
https://nextjs.org/docs/api-routes/introduction
pages/api/* 는 페이지가 아닌 api처럼 동작
client side 코드에는 추가되지 않는다.
handler에 콘솔 추가하고 / useEffect로 fetch 해보기
Dynamic API Routes
https://nextjs.org/docs/api-routes/dynamic-api-routes
dynamic의 동작은 동일
API Middlewares
api config 추가 혹은 다양한 maddlewares 추가 기능
Respone Helpers
response에 담을 수 있는 데이터
정리
Next.js의 라우팅 ⇒ pages 폴더의 file system 활용
Dynamic Routes ⇒ [slug] / [...slug] / [[...slug]]
Router ⇒ 직접 라우터를 조작 가능 push / shallow
API Routes = > API 서버로의 동작 middlewares
본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다
댓글