getInitialProps

00_8_3·2020년 9월 20일
0

getInitialProps란

서버로부터 동적인 데이터를 가져오는 방법중 getInitialProps이 있다.

getInitialProps 는 컴포넌트디드마운트,컴포넌트윌마운트 같은 라이프사이클의 일종으로 넥스트가 임의로 추가해준 라이프 사이클이다.

getInitialProps은 어떤 작업보다도 최초로 실행된다.
( 컴포넌트디드마운트보다도 우선적으로 실행됨)

서버쪽에서 실행될 동작을 수행 할 수있고,
프론트에서도 실행되고 서버에서도 실행된다.

예제

function Page({ stars }) {
  return <div>Next stars: {stars}</div>
}

Page.getInitialProps = async (ctx) => {
  const res = await fetch('https://api.github.com/repos/vercel/next.js')
  const json = await res.json()
  return { stars: json.stargazers_count }
}

export default Page

getInitialProps

receives a single argument called context, it's an object with the following properties:

pathname - Current route. That is the path of the page in /pages
query - Query string section of URL parsed as an object
asPath - String of the actual path (including the query) shown in the browser
req - HTTP request object (server only)
res - HTTP response object (server only)
err - Error object if any error is encountered during the rendering

출처 : https://velog.io/@ykim5470/getInitialProps-app.js-server-client-side-rendering-%EC%A0%95%EB%A6%AC-rkk6ey0bou

https://velog.io/@wndtlr1024/getInitialProps%EB%A1%9C-%EC%84%9C%EB%B2%84-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EB%B0%9B%EA%B8%B0-%EB%8F%99%EC%A0%81%EB%8D%B0%EC%9D%B4%ED%84%B0

https://velog.io/@baramofme/Next.js-%EA%B3%B5%EC%8B%9D-Docs-%ED%9D%9D%EA%B8%B0

0개의 댓글