Next.js - 預渲染



在 Next.js 中,我們知道它會為頁面生成 HTML,這稱為預渲染。Next.JS 支援兩種型別的預渲染。

  • 靜態生成 - 此方法在構建時生成 HTML 頁面。此預渲染的 HTML 在每次請求時都會發送。此方法適用於營銷網站、部落格、電子商務產品列表網站、幫助文件網站。

  • 伺服器端生成 - 此方法在每次請求時生成 HTML 頁面。當 HTML 頁面內容隨每次請求而變化時,此方法適用。

每個頁面的預渲染

Next.JS 允許為每個頁面設定預渲染方法,其中大多數頁面遵循靜態生成,而其他頁面將使用伺服器端渲染。

無資料的靜態生成

可以在沒有資料的情況下進行靜態生成,在這種情況下,HTML 頁面無需預先獲取資料即可準備就緒,然後開始渲染。資料可以在稍後或按請求獲取。此技術有助於在資料需要時間獲取的情況下向使用者顯示使用者介面而無需任何資料。

帶有資料的靜態生成

可以在有資料的情況下進行靜態生成,在這種情況下,HTML 頁面只有在獲取資料後才能準備就緒,因為 HTML 可能依賴於資料。每個元件都有一個特殊的getStaticProps方法,可用於獲取資料並將資料作為頁面的 props 傳遞,以便頁面可以根據傳遞的 props 進行渲染。

getStaticProps() 函式在生產環境中構建時執行,在開發模式下為每個請求執行。

讓我們建立一個示例來演示這一點。

在此示例中,我們將建立一個更新 index.js 和 first.js 頁面以進行伺服器命中以獲取資料。

讓我們更新在全域性 CSS 支援章節中使用的 nextjs 專案。

更新 pages 目錄中的 index.js 檔案以使用 getServerSideProps() 方法。此方法將為每個請求呼叫。

import Link from 'next/link'
import Head from 'next/head'

function HomePage(props) {
   return (
      <>
         <Head>
            <title>Welcome to Next.js!</title>
         </Head>
         <div>Welcome to Next.js!</div>
         <Link href="/posts/first"><a>First Post</a></Link>
         <br/>
         <div>Next stars: {props.stars}</div>
         <img src="/logo.png" alt="TutorialsPoint Logo" />
      </>	    
   )
}

export async function getServerSideProps(context) {
   const res = await fetch('https://api.github.com/repos/vercel/next.js')
   const json = await res.json()
   return {
      props: { stars: json.stargazers_count }
   }
}

export default HomePage

更新 pages 目錄中的 first.js 檔案以使用 getStaticProps() 方法。此方法將呼叫一次。

import Link from 'next/link'
import Head from 'next/head'
import Container from '../../components/container'

export default function FirstPost(props) {
   return (
      <>
         <Container>
            <Head>
               <title>My First Post</title>
            </Head>
            <h1>My First Post</h1>
            <h2>
               <Link href="/">
                  <a>Home</a>
               </Link>
               <div>Next stars: {props.stars}</div>
            </h2>
         </Container>
      </>	  
   )
}

export async function getStaticProps() {
   const res = await fetch('https://api.github.com/repos/vercel/next.js')
   const json = await res.json()
   return {
      props: { stars: json.stargazers_count }
   }
}

啟動 Next.js 伺服器

執行以下命令啟動伺服器:

npm run dev
> nextjs@1.0.0 dev \Node\nextjs
> next

ready - started server on https://:3000
event - compiled successfully
event - build page: /
wait  - compiling...
event - compiled successfully
event - build page: /next/dist/pages/_error
wait  - compiling...
event - compiled successfully

驗證輸出

在瀏覽器中開啟 localhost:3000,您將看到以下輸出。

Home page with data

點選“第一篇文章”連結。

First page with data
廣告