Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Next.js基础文档摘要 #50

Open
fayeah opened this issue Jul 14, 2021 · 0 comments
Open

Next.js基础文档摘要 #50

fayeah opened this issue Jul 14, 2021 · 0 comments
Labels
UI UI test framework/tool

Comments

@fayeah
Copy link
Owner

fayeah commented Jul 14, 2021

一句话描述Next.js

Next.js是React框架,内置了很多功能,比如路由、预渲染、代码分割等等。

重点

目前为止个人觉得里面最值得读的是"Pre-rendering and Data Fetching"。

Pre-rendering and Data Fetching

“Pre-rendering and Data Fetching”是Next.js非常重要的概念之一。默认情况下,next.js会对每一个page进行预渲染,也就是说会提前为每一个page生成HTML,而不是由客户端的JS来生成。预渲染可以带来更好的性能和 SEO 效果。

静态生成和服务端渲染

  • 静态生成:HTML 在 构建时 生成,并在每次页面请求(request)时重用
  • 服务器端渲染:在 每次页面请求(request)时重新生成 HTML。

静态生成的方式可用于:

  • 运营页面
  • 博客
  • 电商产品列表
  • 帮助文档

检验是否要用静态生成:在一个请求之前能不能与渲染?如果是,就应该选择静态生成。

但是,对于经常更新的数据,或者每一个请求内容都不一致的页面,可以使用服务端渲染。相对慢一些,但是预渲染页面总是保持最新的状态。另外一种方式是使用客户端的JS来获取最新的数据。

静态生成使用getStaticProps来获取文件数据、外部API以及数据库等数据,这种方法只在服务端运行,不会在客户端运行,所以getStaticProps相关代码也不会被构建到JS bundle。总的来说,在构建的时候会先去解析getStaticProps,然后进行预渲染。

服务端渲染,使用getServerSideProps,比较慢,因为每次请求都要计算结果,所以应该在需要的时候才使用,例如每次请求都需要获取最新的数据。

以上两种是预渲染的方式,还有一种是不需要预渲染。
客户端渲染,对于用户相关,而与SEO无关的页面,可以使用客户端渲染,先生成页面上静态部分,再利用JS获取外部数据填充到剩余部分,其实这个就是在不使用Next.js时常用的手段不是嘛?

判断页面是否预渲染

  • 打开网页,CMD+SHIFT+P, 禁止JavaScript
  • 刷新页面,如果能正常进行交互则是预渲染,否则不是。
  • 参考页面:point_right: https://create-react-app.now-examples.vercel.app/
    预渲染和非预渲染页面的对比👇 :

预渲染
pre-render1

非预渲染
pre-render

文档链接:https://nextjs.org/learn/basics/data-fetching/pre-rendering
中文文档:https://www.nextjs.cn/docs/basic-features/pages

@fayeah fayeah added the UI UI test framework/tool label Jul 14, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
UI UI test framework/tool
Projects
None yet
Development

No branches or pull requests

1 participant