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:
Contextパラメータとは?
Contextオブジェクトはパラメータとして一緒にこの関数に渡されます.この場合、次のキー値でアクセスできます.この関数はクライアントからではなく、サーバから返されるためです.
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: {},
};
}
};
Reference
この問題について(Next.urlクエリをjsからSSR(feat.typescript)にインポート), 我々は、より多くの情報をここで見つけました https://velog.io/@hhhminme/Next.js에서-SSR로-url-query-가져오기feat.-typescriptテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol