Next.js 数据获取详解
Next.js 数据获取是服务端渲染和静态生成的核心功能,通过预取数据优化首屏加载速度和 SEO 效果。
核心概念
Next.js 数据获取提供三种主要方法:getStaticProps(静态生成)、getServerSideProps(服务器端渲染)、getStaticPaths(动态路径生成)。它们决定了页面在构建时或请求时如何获取数据。
类比传统开发模式:getStaticProps相当于编译时预加载数据,getServerSideProps则像每次打开网页都重新请求数据库。
基础语法
getStaticProps 静态生成
// pages/posts.js
export async function getStaticProps() {
// 从外部API获取数据
const res = await fetch('https://api.example.com/posts');
const data = await res.json();
return {
props: {
posts: data // 将数据作为props传递给页面组件
},
revalidate: 10 // 设置数据刷新间隔(秒)
};
}
getServerSideProps 服务端渲染
// pages/user.js
export async function getServerSideProps(context) {
// 从服务器数据库获取用户信息
const user = await db.users.findUnique({
where: { id: context.query.id }
});
return {
props: {
user // 每次请求都会重新获取数据
}
};
}
getStaticPaths 动态路径
// pages/posts/[id].js
export async function getStaticPaths() {
// 获取所有文章ID列表
const res = await fetch('https://api.example.com/post-ids');
const ids = await res.json();
return {
paths: ids.map(id => ({ params: { id: id.toString() } })),
fallback: 'blocking' // 支持动态生成未预加载的路径
};
}
进阶特性
| 方法 | 执行时机 | 使用场景 | SEO支持 |
|---|---|---|---|
getStaticProps |
构建时 | 博客文章、商品列表 | ✅ |
getServerSideProps |
每次请求 | 用户仪表盘、实时数据 | ✅ |
getStaticPaths |
构建时 | 动态文章页、分类目录 | ✅ |
useSWR |
客户端 | 用户个人资料、评论区 | ❌ |
实战应用
静态博客页面
// pages/blog/[slug].js
export async function getStaticProps(context) {
const { slug } = context.params;
const res = await fetch(`https://api.example.com/blog/${slug}`);
const post = await res.json();
if (!post) {
return { notFound: true }; // 处理404情况
}
return {
props: { post },
revalidate: 60 // 每分钟刷新一次数据
};
}
混合数据获取
// pages/index.js
export async function getStaticProps() {
const [postsRes, settingsRes] = await Promise.all([
fetch('https://api.example.com/posts'),
fetch('https://api.example.com/settings')
]);
return {
props: {
posts: await postsRes.json(),
siteSettings: await settingsRes.json()
}
};
}
注意事项
-
避免过度使用 SSR
每次请求都执行数据库查询会显著增加服务器负载,优先使用getStaticProps的revalidate参数平衡性能与实时性。 -
处理动态路径 404
在getStaticPaths中返回的paths只是预加载路径,未匹配的路径需要单独处理(如使用getStaticProps返回notFound: true)。 -
客户端数据获取陷阱
在页面组件中直接调用 API 会导致 SEO 优化失效,应优先使用getStaticProps或服务端渲染方案。 -
数据获取超时处理
所有数据获取方法默认支持 10 秒超时,复杂查询需要拆分多个异步请求避免阻塞。
总结
Next.js 数据获取通过构建时和请求时的预取策略,解决了传统客户端渲染的 SEO 和性能瓶颈,是现代服务端渲染开发的关键技术。