Next.js 13.4.9数据获取能力解析:新模式与动态获取效果问询
Next.js 13.4.9 全新数据获取模式及动态表现
Next.js 13.4正式稳定了App Router,彻底替代了旧Page Router里的getInitialProps、getServerSideProps等数据获取方式,核心围绕React Server Components(RSC)设计,带来了更简洁、灵活的数据获取逻辑:
一、核心新数据获取模式
1. 组件内直接异步获取(默认Server Component)
App Router下所有组件默认是Server Component,无需额外配置,直接在组件中写async/await执行数据请求,完全在服务器端运行,不会把请求逻辑暴露给客户端:
async function UserProfile() { const resp = await fetch('https://api.company.com/user/12345'); const data = await resp.json(); return <div>用户名:{data.profile.username}</div>; } export default UserProfile;
默认情况下,fetch请求会被自动缓存(GET请求),避免重复请求。
2. 复用性数据获取函数
可以把数据逻辑抽离成独立的异步函数,在多个Server Component中复用,同样在服务器端执行:
// 复用的数据获取逻辑 async function fetchUser(userId: string) { const resp = await fetch(`https://api.company.com/user/${userId}`); if (!resp.ok) throw new Error('获取用户数据失败'); return resp.json(); } // 页面组件 async function UserProfile({ params }: { params: { userId: string } }) { const user = await fetchUser(params.userId); return <div>用户名:{user.profile.username}</div>; }
3. 精细化缓存与重新验证控制
通过fetch的扩展参数,直接控制数据缓存策略,替代旧模式的revalidate配置:
- 强制缓存(默认):
fetch(url, { cache: 'force-cache' })—— 数据缓存至部署更新或主动失效,适合静态数据 - 全动态无缓存:
fetch(url, { cache: 'no-store' })—— 每次用户请求都重新获取数据,等价旧版getServerSideProps - 增量静态重新验证:
fetch(url, { next: { revalidate: 60 } })—— 数据缓存60秒后自动重新验证,适合需要定时更新的内容
4. Server Actions(服务端操作)
针对提交类场景(如表单),无需编写独立API路由,直接在组件内标记异步函数为"use server",即可在服务器端执行数据修改:
// 服务端操作,标记后自动在服务器运行 async function updateUsername(userId: string, newUsername: string) { 'use server'; await fetch(`https://api.company.com/user/${userId}`, { method: 'PUT', body: JSON.stringify({ username: newUsername }), headers: { 'Content-Type': 'application/json' }, }); } async function UserProfile({ params }: { params: { userId: string } }) { const user = await fetchUser(params.userId); return ( <form action={() => updateUsername(params.userId, 'new-username')}> <button type="submit">更新用户名</button> </form> ); }
二、动态数据获取的实际表现
- 零配置SSR:使用
cache: 'no-store'的请求,每次用户访问都会触发服务器端数据获取,返回最新内容,页面渲染完成后再发送到客户端,性能比旧版SSR更优(因为默认Server Component减少客户端JS体积)。 - 自动并行请求:同一组件内的多个独立
fetch请求会被自动并行执行,大幅减少服务器端等待时间,提升页面加载速度。 - 客户端/服务端无缝切换:如果需要在用户交互后获取数据,只需给组件加上
"use client"标记,即可在客户端使用普通fetch或数据状态管理库(如React Query),同时能和Server Component获取的数据无缝结合。 - 原生错误处理:通过App Router的
error.js文件,可以全局捕获数据获取或渲染错误,自动展示友好错误页面,无需手动编写大量try/catch逻辑。
三、与旧模式的对比
你提供的旧版getInitialProps需要在类组件的静态方法中编写数据逻辑,代码冗余且需要处理客户端/服务器端兼容;而新模式直接在组件内编写异步逻辑,默认Server Component减少客户端负载,缓存策略更灵活,整体代码更简洁直观。
内容的提问来源于stack exchange,提问作者Pranavi Khandagale
相关产品推荐
相关产品推荐

