pre-render: 预渲染
1. 静态化
发生的时间:next build
1). 纯静态化
2). SSG: server static generator
getStaticProps: 当渲染组件之前会运行 生成html + json
//该函数只可能在服务端运行
//该函数运行在组件渲染之前
//该函数只能在build期间运行
//返回的对象中的props属性,将被混合到整个组件属性
export async function getStaticProps() {
const resp = await getMovies(1, 20);
return {
props: {
movies: resp.data
}
};
}
getStaticPaths: 当渲染组件之前会运行 解决动态路由
//该函数用于得到有哪些可能出现的id
export async function getStaticPaths() {
const resp = await getMovies();
const paths = resp.data.map(m => ({
params: {
id: m._id
}
}));
console.log("getStaticPaths");
return {
paths,
fallback: true
};
}
fallback:
false: 什么都不做,如果没有静态页面,返回404
true: 会给[id].html
什么时候要使用静态化:
如果你的页面不是根据不同的请求而展示不同,则推荐使用静态化
2. SSR: server side render 服务端渲染
根据每一次请求获取数据,进行渲染
// 每次请求到达后都会运行
// 仅在服务器端运行
// req, res, query
export async function getServerSideProps({ query }) {
const page = +query.page || 1;
console.log("getServerSideProps");
const resp = await getMovies(page, 10);
return {
props: {
movies: resp.data,
page,
total: resp.count,
limit: 10
}
};
}