Next.urlクエリをjsからSSR(feat.typescript)にインポート


Next.JSのSSRの適用方法


Next.jsは今まで12でした.Next.js 9.3バージョンから、プリプレゼンテーション用のデータ取得用のgetInitialiPropsは、getStaticProps、getServerSideProps、getStaticPathsの3つの部分に分かれています.
ここで、今日は主にgetServerSidePropsとgetStaticPropsについて議論します.

getServerSideProps vs getStaticProps


最大の違いはSSRとSSGの違いです.

getStaticProps-SG(Static Site Generation)とは?


If you export a function called getStaticProps (Static Site Generation) from a page, Next.js will pre-render this page at build time using the props returned by getStaticProps.

このWebアプリケーションは、最初の構築(next build)で1回のみ呼び出され、その内容はstatic fileとして構築されます.そのため、後で修正することはできません.

getServerSideProps-SR(ServerSide Rendering)とは?



getServerSideProps only runs on server-side and never runs on the browser. If a page uses getServerSideProps, then:
  • When you request this page directly, getServerSideProps runs at request time, and this page will be pre-rendered with the returned props
  • When you request this page on client-side page transitions through next/link or next/router, Next.js sends an API request to the server, which runs getServerSideProps
  • ページはリクエストを受信するたびに呼び出され、プリプレゼンテーションされます.しかしSSGに比べて効率は低下している.しかし、いつでも内容を動的に変更できるのが利点です.URL内のクエリーを利用してapiを要求した後にpropsにデータを渡すのでgetServerSidePropsを使って開発を試みます.

    Contextパラメータとは?


    Contextオブジェクトはパラメータとして一緒にこの関数に渡されます.この場合、次のキー値でアクセスできます.この関数はクライアントからではなく、サーバから返されるためです.
  • params: If this page uses a dynamic route, params contains the route parameters. If the page name is [id].js , then - params will look like { id: ... }.
  • req: The HTTP IncomingMessage object.
  • res: The HTTP response object.
  • query: An object representing the query string.
  • preview: preview is true if the page is in the Preview Mode and false otherwise.
  • previewData: The preview data set by setPreviewData.
  • resolvedUrl: A normalized version of the request URL that strips the _next/data prefix for client transitions and - includes original query values.
  • typescriptの適用


    typescrptを適用するには、まずGetServerSidePropsというtypeをインポートする必要があります.また、fetchよりもaxiosとtry-catchでpromiseハンドルを実現するのが好きなので、次のコードを書くことができます.
    
    import { GetServerSideProps } from 'next'
    ...
    
    export const getServerSideProps : getServerSideProps = async (context) => {
      try{
      	....
        return {
        	props : {
            	PropsName : data... 
        	}
        }
      } catch(err){
      	console.log(err);
        return {
        	props : {},
        }
      }
    }
    
    次にapiを次のように呼び出します.このときapi urlはです.envを外して開発したほうがいいです.
    あるいは,タイトルが繰り返される場合,それをcustomHookに削除して開発することも一つの方法となる可能性がある.
    export const getServerSideProps: GetServerSideProps = async (context) => {
      try {
        const { menuId } = context.query;
        const response = await axios.get<CategoryType[]>(
          "http://localhost:8080/category/get/menu",
          {
            headers: {
              "Content-Type": "application/json",
              "Access-Control-Allow-Origin": "*",
            },
            params: {
              menuId: menuId,
            },
          }
        );
        const data = response.data;
        console.log(data);
        return {
          props: {
            CategoryData: data,
          },
        };
      } catch (err) {
        console.log(err);
        return {
          props: {},
        };
      }
    };