front-end
The processing flow from the Build step on the Server side up to the Client-side rendering.
採用 pre-rendering 預渲染的方式:SSR、SSG、ISR
Reference
Special Function: useEffect
export default function CSRPage() {
const [dateTime, setDateTime] = React.useState<string>();
React.useEffect(() => {
axios
.get('https://worldtimeapi.org/api/ip')
.then((res) => {
setDateTime(res.data.datetime);
})
.catch((error) => console.error(error));
}, []);
return (
<main>
<TimeSection dateTime={dateTime} />
</main>
);
}
Special Function: getServerSideProps
每次有 request (請求) 的時候在 Server side 執行。除了會產生 HTML 檔案,也會產生 JSON 檔案。
export default function SSRPage({ dateTime }: SSRPageProps) {
return (
<main>
<TimeSection dateTime={dateTime} />
</main>
);
}
export const getServerSideProps: GetServerSideProps = async () => {
// 可以直接抓取資料或是操作資料庫
const res = await axios.get('https://worldtimeapi.org/api/ip');
return {
props: { dateTime: res.data.datetime }, // 傳給該 page 的 props
};
};
Special function: getStaticProps
getStaticProps
會在執行 npm run build 的時候執行並抓取所需要的資料。伺服器跑完該 function 後,除了產生了 HTML 檔案,會另外產生 JSON 檔案。在 Client-side (客戶端) 瀏覽器會讀取該 JSON 檔案裡面的資料用來顯示 page 內容。
// 透過 props 拿到該 page 所需要的資料
export default function SSGPage({ dateTime }: SSGPageProps) {
return (
<main>
<TimeSection dateTime={dateTime} />
</main>
);
}
export const getStaticProps: GetStaticProps = async () => {
const res = await axios.get('https://worldtimeapi.org/api/ip');
return {
// 傳給該 page 的 props
props: { dateTime: res.data.datetime },
};
};
revalidate
參數設定幾秒後拿新的資料重新 Build 與產生頁面。stale-while-revalidate concept
Reference
Reference
可以在 ISR 重 load 幾次資料,會發現有時 server response status code 是 304,代表瀏覽器直接從本身的 cache 讀取內容,所以檔案傳輸非常小。
若使用 Vercel 服務作部署,可留意 Response Headers 中 x-vercel-cache 的值,若為 STALE 代表目前拿到的是在 cache 中的舊版本。
A background request to the origin was made to get a fresh version.
Reference
ISR 很像 SSG,不過它解決了 SSG 不能在 run time 更新資料內容的問題,而且 HTML 檔案也會被 cache 在 CDN 上,減輕對伺服器的負擔(這部分比 SSR 好),網站效能較佳。
Special function: getStaticProps
+ revalidate
在 Next.js 中要啟用 ISR 跟 SSG 的寫法很像,只是要多指定需要 revalidate 的時間
export default function ISR20Page({ dateTime }: ISR20PageProps) {
return (
<main>
<TimeSection dateTime={dateTime} />
</main>
);
}
export const getStaticProps: GetStaticProps = async () => {
const res = await axios.get('https://worldtimeapi.org/api/ip');
return {
props: { dateTime: res.data.datetime },
// 每 60 秒就會 revalidate 一次頁面
revalidate: 60,
};
};
Next.js 可依專案需求支援不同頁面決定要使用 CSR, SSR, SSG, ISR 等不同的渲染方式。
Ans:
https://nextjs.org/docs/basic-features/data-fetching/overview
https://ithelp.ithome.com.tw/m/articles/10267894