6.md
May 17, 2020 · View on GitHub
Pré-renderização e busca de dados
1 -
2 -
3 -
4 -
5 -
6 -
7 -
8 -
9
Dados do blog
Agora, adicionaremos dados de blog ao nosso aplicativo usando o sistema de arquivos. Cada postagem do blog será um arquivo de markdown.
-
Crie um novo diretório de nível superior chamado
posts(não é o mesmo quepages/posts). -
Dentro, crie dois arquivos:
pre-rendering.mdessg-ssr.md.
Copie o seguinte para 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.
Copie o seguinte para 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.
Você deve ter notado que cada arquivo de remarcação possui uma seção de metadados na parte superior, contendo
titleedate. Isso se chama YAML Front Matter, que pode ser analisado usando uma biblioteca chamada gray-matter.
Analisando os dados do blog em getStaticProps
Agora, vamos atualizar nossa página de índice (pages/index.js) usando esses dados. Gostaríamos de:
-
Analisar cada arquivo de remarcação e obter o
title, adatee o nome do arquivo (que serão usados comoidpara o URL da postagem). -
Listar os dados na página de índice, classificados por data.
Para fazer isso na pré-renderização, precisamos implementar o getStaticProps.
Vamos fazer na próxima página!
