当前位置:网站首页>Next. JS static data generation and server-side rendering
Next. JS static data generation and server-side rendering
2022-04-23 11:57:00 【Goldenaarcher】
Next.js Static data generation and server-side rendering
React Although easy to use , But what has been criticized is :SEO optimization problem .Vercel The team is building Next.js I took this problem into account when I was , And provides two SEO Friendly handling , One of them is to use getStaticProps This method .
Take some of the things I wrote before React Small demo For example , Press down f12 Make changes to the page inspect When , Is to be able to see all the code :

However, this is already the case when the client completes rendering , If direct inspect Page source code (chrome Shortcut key ctrl + u), Then you can see :

The page is empty , The remarks are also intimate instructions , If you open this page in a browser , Then you will see an empty page . In this case , Reptiles 、 The robot can't capture the information of the page correctly ,SEO There is no way to talk about .
getStaticProps
How to use getStaticProps
Use getStaticProps Can solve this problem , The reference codes are as follows :
import React from "react";
import EventList from "../components/events/event-list";
// This is util function , Responsible for getting data , It can be from local json Get or get from database In order to get
import {
getFeaturedEvents } from "../helpers/api-util";
const HomePage = ({
featuredEvents }) => {
return (
<div>
<EventList items={
featuredEvents} />
</div>
);
};
export async function getStaticProps(context) {
const featuredEvents = await getFeaturedEvents();
return {
props: {
featuredEvents: featuredEvents,
},
revalidate: 1800,
};
}
export default HomePage;
The rendering effect is as follows :

The source code of the page is as follows :

The source code is Next.js Directly pack and compress , So it looks messy , But you can also see , The data on the page is truly reflected in the source code , And when robots / When a crawler crawls a page , You can also grab the following keywords :
- event
- extroverts
- introverts
- Relevant location
- Related events
For users , When they search for the above keywords in the search engine , It is possible to browse to the generated web page .
Notice this code :revalidate: 1800, although getStaticProps It's a page built when packaging , however Next.js Itself is through node Implemented the server , Therefore, it can also be rebuilt after the deployment goes online (rebuild) page , This is the time Next.js Will check getStaticProps If there revalidate This return value .
Some words Next.js The static rendered page will be regenerated after the specified time , And return the latest page to the user . If you use Next.js Build a blog system , On the front page revalidate It can be set to 1 God ( namely 86400s, That is to say revalidate: 86400), After all, under normal circumstances, the most blogs are still day shift .
In this case , The project will be restarted regularly every day build, Reptiles / Robots can also catch the latest pages .
When to use getStaticProps
Next.js The following situations mentioned in the official documents of will be more suitable for use getStaticProps:
-
The data required to render the page is available at build time ahead of a user’s request
Page data before user access 、 pack (build) It already exists
-
The data comes from a headless CMS
The data comes from headless content management systems (CMS - Content Management System)
headless It means separating the front end from the back end , The obtained content can run on a variety of platforms .
-
The data can be publicly cached (not user-specific)
Information is not user specific , The cache can be exposed . There is no important information , For example, token such .
-
The page must be pre-rendered (for SEO) and be very fast —
getStaticPropsgenerates HTML and JSON files, both of which can be cached by a CDN for performancePage requirements must be SEO friendly , And the construction speed is very fast . adopt
getStaticPropsBuilt HTML and JSON All the documents are available through CDN Caching improves performance .
getStaticProps The elapsed time
-
getStaticPropsalways runs during next buildEvery time build when
-
getStaticPropsruns in the background when using revalidateWhen
revalidatetime out -
getStaticPropsruns on-demand in the background when usingunstable_revalidateWhen using
unstable_revalidatewhen ,unstable_revalidateIs still in the beta period , I should wait until this feature is officially released before going to seeunstable_revalidateSpecific functions
getServerSideProps
except getStaticProps outside ,Next.js The team also provides another way to get data dynamically , That's using getServerSideProps. And getStaticProps comparison ,getServerSideProps A new page will be generated and returned to the user every time the user visits , That is, the true sense of server-side rendering (server side rendering).
Its usage and getStaticProps be similar , No, revalidate attribute , The code looks like this :
export async function getServerSideProps(context) {
return {
props: {
}, // will be passed to the page component as props
};
}
getStaticProps in context Not many parameters , however getServerSideProps Contains some parameters on the server side , Such as :
- params
- req
- res
- query
- …
because getStaticProps and getServerSideProps Your code will not be exposed to the front end , So you can add some pairs here header, req/res Something like that .
More of this part belongs to node.js The category of part , I won't go into details here .
版权声明
本文为[Goldenaarcher]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231152018231.html
边栏推荐
- Step function of activation function
- On lambda powertools typescript
- Laravel always returns JSON response
- The way to change children's programming structure
- Overall plan management mode in maker Education
- Analyze the rules for the use of robots with good performance
- Fabric 1.0 source code analysis (33) implementation of peer channel command and subcommand
- The fourth chapter is to enable the filling object of IM and enable ADO for im column storage (IM 4.8)
- Usage record of map < qstring, bool >
- IM表达式如何工作(5.3)
猜你喜欢

Simple construction of rebbitmq

Interpreting the art created by robots

Use kettle to copy records to and get records from results

激活函数之sigmoid函数
![A detailed explanation of head pose estimation [collection of good articles]](/img/59/6ac8692b0dbd0218bb512c5eac3124.png)
A detailed explanation of head pose estimation [collection of good articles]

5个免费音频素材网站,建议收藏

Overall plan management mode in maker Education
![[Web 每日一练] 八色拼图(float)](/img/59/474080f6377b3684aa4fb2a39e1d81.png)
[Web 每日一练] 八色拼图(float)

Nacos Basics (5): getting started with Nacos configuration

Analyze the rules for the use of robots with good performance
随机推荐
How to expand the capacity of the server in the 100 million level traffic architecture? Well written!
Laravel增加自定义助手函数
激活函数之sigmoid函数
Blog post navigation (real-time update)
Purpose of IM expression (IM 5.2)
IDEA 代码质量规范插件SonarLint
How Im expressions work (5.3)
博客文章导航(实时更新)
外包干了五年,废了...
使用连接组优化连接 (IM 6)
配电房远程综合监控系统在10kV预制舱项目中的应用
云呐|固定资产盘点中,支持多种盘点方式(资产清查盘点)
Nacos Foundation (7): Configuration Management
5-minute NLP: text to text transfer transformer (T5) unified text to text task model
Cognition and R & D technology of micro robot
欣旺达宣布电池产品涨价 此前获“蔚小理”投资超10亿
Laravel always returns JSON response
MQ is easy to use in laravel
Practical data Lake iceberg lesson 30 MySQL - > iceberg, time zone problems of different clients
力扣-70.爬楼梯