一起來學 next.js - getServerSideProps 篇
theme: devui-blue
持續創作,加速成長!這是我參與「掘金日新計劃 · 10 月更文挑戰」的第12天,點選檢視活動詳情
getServerSideProps
是 next.js
中的一項特色功能,可以讓我們在給頁面設定一些初始的 props
引數。
使用
getServerSideProps
是定義在頁面中的 API
,但是其執行環境是 node
端,而不是客戶端,一般常見使用場景為:
- 頁面前置許可權校驗
- 頁面必備引數獲取
使用時需要在對應的 page
檔案中 export getServerSideProps
js
const Page = props => {
return <div>page</div>;
};
export async function getServerSideProps(context) {
return {
props: {}
};
}
export default Page;
這樣便可以從頁面元件中直接使用 props
來獲取 getServerSideProps
注入的 props
了。
ts 定義
如果是在 TS
中 next.js
也提供了 GetServerSideProps
介面來方便智慧提示。
ts
import { GetServerSideProps } from 'next';
export const getServerSideProps: GetServerSideProps = async context => {
return {
props: {}
};
};
context
getServerSideProps
中的 context
引數包含了常用的請求的 req
、res
、params
、query
等引數,還包含了 preview
、previewData
、resolvedUrl
、locale
等引數
實現
當 getServerSideProps
所在頁面為 SSR
服務端渲染時,getServerSideProps
中的資料將會被放到全域性的 _NEXT_DATA
中,用於 hydrate
。
而非 SSR
情況下,進入該頁面 next.js
將會自動發請求到: _next/data/development/{url}.json?{query}
,其中 development
為開發環境下地址段,該請求的返回值為:
json
{
"pageProps": "返回的 props 資料內容",
"__N_SSP": true
}
從而將 getServerSideProps
返回值在頁面掛載時注入進去。
請求 API
需要注意 getServerSideProps
為 node server
端程式碼,無法在其中直接請求內部 API
,因為會找不到地址(外部 API
可以請求,認為是這段程式碼是獨立的 node
端程式碼就行了)。如果想要呼叫內部 API
可以將對應的 API handler
拆解,作為方法呼叫。
```ts // api/test.ts export const getContent = async () => { return content; };
export default async function handler(req: NextApiRequest, res: NextApiResponse
```ts // pages/page.tsx import { getContent } from './api/test.ts';
export const getServerSideProps: GetServerSideProps = async context => { return { props: await getContent() }; }; ```
問題
還有一點需要注意的是,雖然 getServerSideProps
為 server
端程式碼,但是客戶端打包時好似仍然會將對應的程式碼打包到頁面中,所以應當儘量避免其中有過於複雜的邏輯或引入一些較大的包。
特殊處理 - 404、跳轉、異常
getServerSideProps
返回值除了可以設定 props
外還可以使用 notFound
來強制頁面跳轉到 404。
```tsx export async function getServerSideProps(context) { const data = await getData();
if (!data) {
return {
notFound: true
};
}
return {
props: { data }
} ```
或者是使用 redirect
來將頁面重定向。
```tsx export async function getServerSideProps(context) { const data = await getData();
if (!data) {
return {
redirect: {
destination: '/',
permanent: false
}
};
}
return {
props: { data }
};
} ```
並且如果 getServerSideProps
報錯了,next.js
將會直接跳轉到 500 頁面,又省下一段異常處理程式碼,可喜可賀。
總結
通過 next.js
的 getServerSideProps
,我們在開發中可以很好的協調前後端資料,一些頁面初始化資料、頁面鑑權可以直接在 getServerSideProps
中進行處理,這樣可以大大簡化頁面邏輯,還保障前後端的統一性。