Custom ` App ` - connect-foundation/2019-10 GitHub Wiki
Next.js๋ App component๋ฅผ ํ์ด์ง๋ฅผ ์ด๊ธฐํ ํ๋๋ฐ ์ฌ์ฉํฉ๋๋ค. ์ฌ์ฉ์๋ ์ด๋ฅผ ์ค๋ฒ๋ผ์ด๋ ํ ์ ์๊ณ ๋ํ ํ์ด์ง ์ด๊ธฐํ ๊ณผ์ ์ ์ ์ดํ ์ ์์ต๋๋ค. ์๋์ ๋ช
์๋ ๊ฒ๋ค์ ๊ฐ๋ฅํ๊ฒ ํด์ค๋๋ค.
- ํ์ด์ง ๋ณํ์ฌ์ด์ layout์ ์ง์ํ ์ ์์ต๋๋ค.
- ํ์ด์ง๋ฅผ ๋ค๋น๊ฒ์ดํ ํ๋ ๋์ state๋ฅผ ์ ์งํ ์ ์์ต๋๋ค.
-
componentDidCatch๋ฅผ ์ด์ฉํ์ฌ ์ปค์คํ ์๋ฌ ํธ๋ค๋ง์ด ๊ฐ๋ฅํฉ๋๋ค. - ํ์ด์ง์ ์ถ๊ฐ์ ์ธ ๋ฐ์ดํฐ๋ฅผ ์ฃผ์ ํ ์ ์์ต๋๋ค. (for example by processing GraphQL queries)
์ค๋ฒ๋ผ์ด๋ ํ๊ธฐ ์ํด์ , ./pages/_app.js ํ์ผ์ ๋ง๋ค๊ณ , ์๋์ ๊ฐ์ด App class ๋ฅผ ์ค๋ฒ๋ผ์ด๋ ํด์ผํฉ๋๋ค.
import React from 'react'
import App from 'next/app'
class MyApp extends App {
// Only uncomment this method if you have blocking data requirements for
// every single page in your application. This disables the ability to
// perform automatic static optimization, causing every page in your app to
// be server-side rendered.
//
// static async getInitialProps(appContext) {
// // calls page's `getInitialProps` and fills `appProps.pageProps`
// const appProps = await App.getInitialProps(appContext);
//
// return { ...appProps }
// }
render() {
const { Component, pageProps } = this.props
return <Component {...pageProps} />
}
}
export default MyAppNote: ์ปค์คํ
getInitialProps๋ฅผ App ์ ์ถ๊ฐํ๋ฉด Automatic Static Optimization์ด ๋์ํ์ง ์์ต๋๋ค.
Next.js๋ ์๋์ผ๋ก ํด๋น ํ์ด์ง๊ฐ blocking data๊ฐ ํ์๋ก ํ์ง ์๋ ๊ฒฝ์ฐ ์๋์ ์ผ๋ก ํ์ด์ง๋ฅผ prerenderํฉ๋๋ค. ์ด ์ฌ๋ถ๋ ํด๋น ํ์ด์ง ๋ด์ getInitialProps์ ์ฌ๋ถ๋ก ํ๋จํฉ๋๋ค.
getInitialProps ๊ฐ ์กด์ฌํ๋ฉด, Next.js ๋ ํด๋น ํ์ด์ง๋ฅผ ์ ์ ์ผ๋ก ์ต์ ํํ์ง ์์ต๋๋ค. ๋์ ์ Next.js ๋ ๊ธฐ๋ณธ ๋์์ ์ฌ์ฉํ์ฌ ์์ฒญ์ ๋ฐ๋ผ ์์ฒญ์ ํ์ด์ง๋ฅผ ๋ ๋๋งํฉ๋๋ค.(์๋ฒ ์ธก ๋ ๋๋ง์ ์๋ฏธํฉ๋๋ค.)
getInitialProps ๊ฐ ์กด์ฌํ์ง ์์ผ๋ฉด, Next.js๊ฐ ์๋์ ์ผ๋ก ์ ์ ์ธ html์ prerenderingํจ์ผ๋ก์จ ํ์ด์ง๋ฅผ ์ ์ ์ผ๋ก ์ต์ ํํฉ๋๋ค. prerendering ํ๋ ๋์์๋ ์ ๊ณตํ query์ ๋ณด๊ฐ ์กด์ฌํ์ง ์๊ธฐ ๋๋ฌธ์ router์ query ์ค๋ธ์ ํธ๋ ๋น์ด์์ต๋๋ค. ๋ชจ๋ query ๊ฐ์ ์ํ ํ ํด๋ผ์ด์ธํธ ์ธก์ ์ฑ์์ง๋๋ค.
์ด ๊ธฐ๋ฅ์ ํตํด Next.js๋ ์๋ฒ ๋ ๋๋ง ๋ฐ ์ ์ ์ผ๋ก ์์ฑ ๋ ํ์ด์ง๊ฐ ๋ชจ๋ ํฌํจ ๋ ํ์ด๋ธ๋ฆฌ๋ ์ ํ๋ฆฌ์ผ์ด์ ์ ์์ฑ ํ ์ ์์ต๋๋ค. ๋ฐ๋ผ์ Next.js ๋ ํญ์ ๊ธฐ๋ณธ์ ์ผ๋ก ๋น ๋ฅธ ์์ฉ ํ๋ก๊ทธ๋จ์ ์์ฑํฉ๋๋ค.
import React from 'react'
import App from 'next/app'
class Layout extends React.Component {
render () {
const { children } = this.props
return <div className='layout'>{children}</div>
}
}
export default class MyApp extends App {
render () {
const { Component, pageProps } = this.props
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
}
}