SSR与Static generation
获取数据的 API 分为 2 种:静态导出和 SSR。涉及三个 api: getStaticProps()
、 getStaticPaths()
、 getServerSideProps()
。
# Static generation
运行时机:next 进行 build 的时候执行相关函数。
运行环境:node 环境
需要用到 getStaticProps()
、 getStaticPaths()
这两个接口,执行顺序是:getStaticPaths => getStaticProps。作用如下:
- getStaticPaths:生成当前路由的信息,在 getStaticProps 方法种可以获取到
- getStaticProps:生成组件的 props 数据
// pages/posts/[id].jsx
const PostPage = () => { ... }
export default PostPage;
export async function getStaticPaths() {
const paths = [{ params: { id: "1" } }, { params: { id: "2" } }];
// We'll pre-render only these paths at build time.
// { fallback: false } means other routes should 404.
return {
paths,
fallback: false,
};
}
export async function getStaticProps(props) {
console.log('props is', props)
return {
props: {
...props,
name,
},
};
}
以上面代码为例,访问 http://localhost:3000/posts/2?name=123 的时候,会打印: props is { params: { id: '2' } }
问题:getStaticPaths 返回的 fallback 为 true 和 false 的区别?
如果 fallback 为 true,那么在 router 上识别相关属性,进行如下处理:
import { useRouter } from 'next/router'
function Post({ post }) {
const router = useRouter()
// If the page is not yet generated, this will be displayed
// initially until getStaticProps() finishes running
if (router.isFallback) {
return <div>Loading...</div>
}
// Render post...
}
如果 fallback 为 false,那么返回 404 页面,对应的页面组件名是 _error.js
。
问题:怎么获取动态数据?
动态数据来源于本机和远程。本机可以是 markdown 文件,远程可以是调用接口。getStaticPaths 和 getStaticProps 都是 node 环境,可以直接使用核心库或者三方 sdk。
注意:引入 node 环境的库时,有两种做法。
- getStaticPaths 和 getStaticProps 进行
require(...)
- 直接在全局 import,例如
import fs from 'fs'
。但是一定要在 getStaticPaths 和 getStaticProps 使用被引用的库,否则会出问题。
import fs from "fs";
export async function getStaticProps(props) {
// 这个地方必须要用,fs才不会报错
const name = fs.close.toString();
return {
props: {
...props,
name,
},
};
}
# SSR
运行时机:build 时候不执行,每次新请求执行。
运行环境:node 环境
接口: getServerSideProps()
当使用 SSR 的相关接口,就不能使用 static generation 的相关接口。在 getServerSideProps 中,参数中包含了前端请求接口的路由信息(路由信息由请求方确认,所以不需要 static generation 中还需要 getStaticPaths 来生成)。
# Static generation 和 SSR 的区别
本质在于数据获取的时机,也就是相关接口运行时机。
以 static generation 为例:执行 build 命令,控制台才会输出。
以 ssr 为例:执行 build,无输出;执行 start,用户访问才会有输出。
# 请求工具
推荐使用 axios.js