210329 ~ 31_TIL / getServerSideProps

김승훈·2021년 4월 16일
0

flow-clone_TIL

목록 보기
9/12

29 일

  1. 모달 딤드 처리
const Modal = ({visible, children}) => {
  return (
    <>
    <ModalOverlay visible={visible} />
    <ModalWrapper visible={visible}>
        {children}
    </ModalWrapper>
    </>
  );
};

<Modal visible={false}>
  <ProjectMakeForm />
 </Modal>

모달이 여러개 일 경우 어떻게 관리하면 좋을 까 ..?

30일

  1. 프로젝트 방 상세 작업을 위한 동적 라우팅
    page 폴더안에 detail/[id].js

query: Object-객체로 구문 분석 된 쿼리 문자열입니다. 페이지에 데이터 가져 오기 요구 사항 이없는 경우 사전 렌더링 중에 빈 개체가됩니다 . 기본값은{}

일반적인 사용

  • pages/post/[id].js ⇒ post/1 로 접근가능

예시 1

import { useRouter } from 'next/router'

const Post = () => {
  const router = useRouter()
  const { id } = router.query

  return <p>Post: {id}</p>
}

export default Post

예시 2

  • pages/post/[id].js 에 대해 post/abc?test=123 로 접근했을 때 갖는 query object는 ?
{ "id" : "abc", "test" : "123" }

출처:

https://programming119.tistory.com/233

[개발자 아저씨들 힘을모아]

https://velog.io/@silver2473/Next.js의-장점-2

31일

  1. 프로젝트 상세 퍼블리싱 중 및 디자인 변경으로 구조변경
  2. 콘텐츠 높이 값이 가변적이여서 flex로 변경

서버사이드 렌더링

getStaticProps

아래와 같이 async를 사용하여 export하게 되면 Next.js에서는 빌드할 때 해당 페이지를 Pre-render한다.

const Blog = ({ posts }) => {
  return (
    <ul>
      {posts.map((post) => (
        <li>{post.title}</li>
      ))}
    </ul>
  );
};

export async function getStaticProps() {
  // 외부 데이터를 불러올 수 있다.
  const res = await fetch("https://.../posts");
  const posts = await res.json();

  //  { props: posts } 이렇게 return 해주면  Blog 페이지는 빌드타임시에 post를 가져온다.

  return {
    props: {
      posts,
    },
  };
}

export default Blog;

getStaticProps를 써야할 때는 언제?

Next.js 공식문서에는 아래와 같을 때 쓰라고 나와있다.

  • 유저가 request 하기에 앞서서 페이지를 렌더링 할때 필요한 데이터가 있을 때
  • 데이터가 headless CMS로부터 올때 (이건 무슨말인지 모르겠음)
  • 데이터가 공식적으로 캐싱될 수 있을 때 (특저 유저가 아닌)

그러니까 쉽게 말해 그냥 거의 외부에서 API를 통해 데이터를 가져와 렌더링하는 모든 페이지는 써도 무방한 듯하다.

주의해야할 점은 client사이드에서 절대로 실행되지 않는다. bundle.js에도 없다!

오히려 getServerSideProps을 써야할 때가 언제인지 아는게 좋다. 그 내용은 이어서 설명하겠다.


getServerSideProps

getServerSideProps를 사용하는 방법은 동일히다. async로 export 해주게 되면 매 requeset 때마다 페이지에 있는 내용들을 pre-render해 줄것이다.

export async function getServerSideProps(context) {
  return {
    props: {}, //페이지의 초기 prop값으로 전달됨.
  };
}
```jsx
뭐 사용방법도 거의 완전 동일하다.

```jsx
function Page({ data }) {
  // Render data...
}

// This gets called on every request
export async function getServerSideProps() {
  // Fetch data from external API
  const res = await fetch(`https://.../data`);
  const data = await res.json();

  // Pass data to the page via props
  return { props: { data } };
}

export default Page;

클라이언트 사이드에서 실행되지 않는 것과 page에서만 사용할 수 있다는 내용 역시 동일하다.

https://yohanpro.com/posts/nextjs/data-fetching

https://velog.io/@ansrjsdn/Next.js-9.3-Data-fetching

https://kyounghwan01.github.io/blog/React/next/getInitialProps/#getinitialprops-이점


https://nunucompany.tistory.com/5

0개의 댓글