扫码一下
查看教程更方便
在 next.js 中,我们知道它会为称为预渲染的页面生成 html。 next.js 支持两种类型的预渲染。
next.js 允许为每个页面设置预渲染方法,其中大部分页面遵循静态生成,其他页面将使用服务器端渲染。
静态生成可以在没有数据的情况下完成,在这种情况下,html 页面将准备就绪,无需预取数据然后开始渲染。 可以稍后或根据请求获取数据。 这种技术有助于在没有任何数据的情况下向用户显示用户界面,以防数据需要时间。
静态生成可以用数据完成,在这种情况下,html 页面在获取数据之前不会准备好,因为 html 可能依赖于数据。 每个组件都有一个特殊的方法 getstaticprops
可以用来获取数据并将数据作为页面的 props 传递,以便页面可以根据传递的 props 进行渲染。
getstaticprops() 函数在生产中的构建时运行,并在开发模式下每个请求都会运行。
让我们创建一个示例来看一下。
在此示例中,我们将创建一个更新 index.js 和 first.js 页面,从而使服务器命中来获取数据。
让我们更新 全局 css 支持 章节 中使用的 nextjs 项目。
更新 pages 目录中的 index.js 文件以使用 getserversideprops() 方法。 此方法将根据请求调用。
index.js
import link from 'next/link' import head from 'next/head' function homepage(props) { return ( <>
welcome to 迹忆客 - next.js 教程! welcome to 迹忆客 - next.js 教程!
next stars: {props.stars}) } export async function getserversideprops(context) { const res = await fetch('https://api.github.com/repos/vercel/next.js') const json = await res.json() return { props: { stars: json.stargazers_count } } } export default homepage
first.js
import link from 'next/link' import head from 'next/head' import container from '../../components/container' export default function firstpost(props) { return ( <>
) } export async function getstaticprops() { const res = await fetch('https://api.github.com/repos/vercel/next.js') const json = await res.json() return { props: { stars: json.stargazers_count } } } my first post
next stars: {props.stars}
运行以下命令启动服务器
$ npm run dev
在浏览器中打开 localhost:3000 ,我们将看到以下输出。
点击first post 链接。