【NEXT.JS 系列】預先渲染和數據獲取 4

Home 教學 【NEXT.JS 系列】預先渲染和數據獲取 4
【NEXT.JS 系列】預先渲染和數據獲取 4
Next.js

部落格資料

我們現在將使用檔案系統將部落格資料添加到我們的應用程式中。 每篇文章都將是一個 markdown 文件。

  • 建立一個名為 posts 的新頂層目錄(這與 pages/posts 不同)。
  • posts 中,建立兩個文件:pre-rendering.mdssg-ssr.md

現在,將以下程式碼複製到 posts/pre-rendering.md

---
title: 'Two Forms of Pre-rendering'
date: '2020-01-01'
---

Next.js has two forms of pre-rendering: **Static Generation** and **Server-side Rendering**. The difference is in **when** it generates the HTML for a page.

- **Static Generation** is the pre-rendering method that generates the HTML at **build time**. The pre-rendered HTML is then _reused_ on each request.
- **Server-side Rendering** is the pre-rendering method that generates the HTML on **each request**.

Importantly, Next.js lets you **choose** which pre-rendering form to use for each page. You can create a "hybrid" Next.js app by using Static Generation for most pages and using Server-side Rendering for others.

然後,將以下程式碼複製到 posts/ssg-ssr.md

---
title: 'When to Use Static Generation v.s. Server-side Rendering'
date: '2020-01-02'
---

We recommend using **Static Generation** (with and without data) whenever possible because your page can be built once and served by CDN, which makes it much faster than having a server render the page on every request.

You can use Static Generation for many types of pages, including:

- Marketing pages
- Blog posts
- E-commerce product listings
- Help and documentation

You should ask yourself: "Can I pre-render this page **ahead** of a user's request?" If the answer is yes, then you should choose Static Generation.

On the other hand, Static Generation is **not** a good idea if you cannot pre-render a page ahead of a user's request. Maybe your page shows frequently updated data, and the page content changes on every request.

In that case, you can use **Server-Side Rendering**. It will be slower, but the pre-rendered page will always be up-to-date. Or you can skip pre-rendering and use client-side JavaScript to populate data.

您可能已經注意到每個 markdown 文件的頂部都有一個 metadata 部分,其中包含 titledate。 這稱為 YAML Front Matter,可以使用名為 gray-matter 的函式庫進行解析。

在 getStaticProps 上解析部落格資料

現在,讓我們使用這些資料更新我們的索引頁面(pages/index.js)。 我們希望:

  • 解析每個 markdown 文件並獲取 titledate 和文件名(將用作文章 URL 的 id)。
  • 列出索引頁上的資料,按日期排序。

要在預先渲染中執行此操作,我們需要實現 getStaticProps

下一頁我們來實做吧!

相關文章