개발노트

next - getInitialProps 본문

React/project

next - getInitialProps

aloha2jh 2020. 8. 27. 20:02

CSR(client side rendering)의 문제점

ex) front의 useEffect로 로그인여부를 확인할 경우,

front UI (데이터가없는)가 먼저 로드되서 요청보내고 응답이 온 후에 UI가 바뀜.

잠깐사이지만 로그인 안되있을때 화면이 보이는 문제 발생

컴포넌트가 마운트 되고나서 데이터를 불러오기때문에 데이터없는 화면이 보이는 문제

(이걸 로딩바 돌아가는 화면으로 대체가 가능하기도 하다)

 

next의 getInitialProps

getInitialProps로 서버쪽 데이터를 미리 불러와서 front를 렌더링 하는게 가능해짐

 

사전에불러와야할 데이터- Data Fetching

즉 Data Fetching을 서버에서 하게 되는것

 

 

 

 

 

(1) express랑 next연결

//front/server.js
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(()=>{
    const server = express();
    //server.use(morgan('dev')); 
}

getInitialProps는 next에서 임의로 넣어주는 라이프사이클이기 때문에,

router는 express를 사용할거라서, express와 next를 연결.

 

(2) front server router

    server.get('/hashtag/:tag', (req,res)=>{  // hashtag/blabla로 들어오면
        return app.render(req, res, '/hashtag' ,{tag:req.params.tag});  
        // front/pages/hashtag.js 로 렌더링되게
    });

hashtag페이지로 시작되는 :와일드카드 요청을 받으면 서버에서 어떤단어인지 받아야하기때문에, 내용을 req.params.tag로 보내줌

 

 

(3) _app.js에 getInitialProps를 추가

<Component /> -> 부분이 pages 안에있는 컴포넌트들인데만약 component가 .getInitialProps메서드를 가지고 있을 경우, ctx를 넘겨준다

 

context.ctx는 next가 넣어주는 정보들.

RoundBird.getInitialProps = async(context)=>{ // next가 context를 넣어줌 
    console.log(context);
    const { ctx, Component } = context;
    let pageProps = {};
    if( Component.getInitialProps ){
        await Component.getInitialProps(ctx);
    }
    return { pageProps };
}

 

 

(4) pages/Hashtag.js 에 .getInitialProps를추가

Hashtag.getInitialProps = async (contextCTX)=>{
    console.log('------', contextCTX.query.tag);
}

 Hashtag.js 페이지를 실행할경우 ctx 를넘겨 받게 된다

 

 

context 라는 next가 넘겨주는 component,router,ctx

{
...
  ctx: {
    err: undefined,
    req: IncomingMessage {
      _readableState: [ReadableState],
    ...
    },
    res: ServerResponse {
      _events: [Object: null prototype],
    ...
    },
    pathname: '/hashtag',
    query: { tag: '단어' },  ////
    asPath: '/hashtag/%EB%8B%A8%EC%96%B4',
    AppTree: [Function: AppTree],
    store: {
      dispatch: [Function],
    ...
    },
    isServer: true
  }
}

'React > project' 카테고리의 다른 글

nodemon  (0) 2020.08.27
redux 설치  (0) 2020.08.25
redux  (0) 2020.08.25
back 서버실행  (0) 2020.08.20
back 세팅  (0) 2020.08.20