25
章节25
实现 getStaticProps
Next.js 中的预渲染
Next.js 有两种预渲染形式:静态生成 和 服务器端渲染。 区别在于 何时 为页面生成 HTML。
- 静态生成 是一种预渲染方法,它在 构建时 生成 HTML。 预渲染的 HTML 在每次请求时都会被重用。
- 服务器端渲染 是一种预渲染方法,它在 每次请求 时生成 HTML。
重要的是,Next.js 允许你 选择 每页使用哪种预渲染形式。 你可以通过对大多数页面使用静态生成,对其他页面使用服务器端渲染来创建一个“混合” Next.js 应用程序。
使用静态生成 (getStaticProps()
)
现在,我们需要为 getSortedPostsData
添加一个导入,并在 pages/index.js
中的 getStaticProps
中调用它。
在你的编辑器中打开 pages/index.js
,并在导出的 Home
组件上方添加以下代码
import { getSortedPostsData } from '../lib/posts';
export async function getStaticProps() {
const allPostsData = getSortedPostsData();
return {
props: {
allPostsData,
},
};
}
通过在 getStaticProps
的 props
对象中返回 allPostsData
,博客文章将作为 prop 传递给 Home
组件。 现在你可以像这样访问博客文章
export default function Home ({ allPostsData }) { ... }
要显示博客文章,让我们更新 Home
组件,添加另一个 <section>
标签,并将数据放在包含自我介绍的部分下方。 别忘了还将 props 从 ()
更改为 ({ allPostsData })
export default function Home({ allPostsData }) {
return (
<Layout home>
{/* Keep the existing code here */}
{/* Add this <section> tag below the existing <section> tag */}
<section className={`${utilStyles.headingMd} ${utilStyles.padding1px}`}>
<h2 className={utilStyles.headingLg}>Blog</h2>
<ul className={utilStyles.list}>
{allPostsData.map(({ id, date, title }) => (
<li className={utilStyles.listItem} key={id}>
{title}
<br />
{id}
<br />
{date}
</li>
))}
</ul>
</section>
</Layout>
);
}
如果你访问 https://:3000,现在你应该能看到博客数据了。

恭喜! 我们已成功获取了外部数据(来自文件系统),并使用此数据预渲染了索引页面。

让我们来谈谈在下一页上使用 getStaticProps
的一些技巧。
这有帮助吗?