Next.js最佳实践:是否仅在SSG/SSR中使用Axios?
Next.js 数据获取最佳实践:Axios vs SSG/SSR 函数
核心结论:不是“非此即彼”,而是按需选择
Next.js 提供的 SSG/SSR 数据获取函数(getStaticProps、getServerSideProps、getStaticPaths)和组件内用 Axios 这类工具做客户端请求,是互补而非替代的关系,关键看你的数据需求和页面性能目标。
什么时候优先用 SSG/SSR 相关函数?
- 需要预渲染页面核心内容:如果页面数据是静态或准静态的(比如博客文章、产品详情),用
getStaticProps可以在构建阶段把数据和页面一起生成静态 HTML,用户访问时直接加载,速度最快且 SEO 友好。 - 需要服务器实时数据:如果页面数据需要每次请求都从服务器获取最新值(比如用户专属内容、实时统计数据),用
getServerSideProps会在每次请求时在服务器端拉取数据,再渲染完整页面返回给客户端,保证数据新鲜度。 - 避免客户端请求延迟:服务器端数据获取能让页面加载时就带上完整内容,不会出现客户端请求完成前的空白或 loading 状态,提升首屏用户体验。
举个 getStaticProps 的简单示例:
export async function getStaticProps() { // 服务器端环境下,用 Axios 或 fetch 拉取数据都可以 const res = await axios.get('https://api.example.com/posts'); const posts = res.data; return { props: { posts }, // 传递给页面组件的参数 revalidate: 60, // 可选:开启增量静态再生,每60秒重新生成页面 }; } export default function Posts({ posts }) { return ( <div className="post-list"> {posts.map(post => ( <article key={post.id}> <h2>{post.title}</h2> <p>{post.excerpt}</p> </article> ))} </div> ); }
什么时候适合在组件内用 Axios?
- 动态交互触发的数据获取:比如用户点击按钮、提交表单后加载筛选结果、加载更多内容,这类场景只能在客户端触发,适合用 Axios 发起请求。
- 依赖客户端状态的数据:比如用户登录后获取个人信息、购物车内容,这类数据依赖客户端存储的 token 或用户标识,无法在服务器端预渲染,必须在组件内请求。
- 非关键辅助数据:比如页面侧边栏的推荐内容、评论区,即使加载慢一点也不影响核心体验,可以放在客户端请求,减轻服务器或构建阶段的压力。
举个组件内用 Axios 的示例:
import { useState, useEffect } from 'react'; import axios from 'axios'; export default function UserProfile() { const [userInfo, setUserInfo] = useState(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(''); useEffect(() => { const fetchUserInfo = async () => { try { const authToken = localStorage.getItem('auth_token'); const res = await axios.get('https://api.example.com/user/profile', { headers: { Authorization: `Bearer ${authToken}` } }); setUserInfo(res.data); } catch (err) { setError('获取用户信息失败,请稍后重试'); } finally { setIsLoading(false); } }; fetchUserInfo(); }, []); if (isLoading) return <div className="loading">加载中...</div>; if (error) return <div className="error">{error}</div>; return ( <div className="profile"> <h1>欢迎回来,{userInfo.nickname}</h1> <p>邮箱:{userInfo.email}</p> </div> ); }
额外注意点
- 服务器端可以混用 Axios:在
getStaticProps或getServerSideProps里,依然可以用 Axios 发起请求,不用刻意替换成 fetch,选你顺手的工具即可。 - 客户端请求要做好状态处理:用 Axios 做客户端请求时,必须处理 loading、error 状态,避免用户看到空白或无提示的错误。
- SEO 优先级:如果内容需要被搜索引擎抓取,优先用 SSG/SSR;如果是用户交互后的动态内容,SEO 影响不大,可以用客户端请求。
内容的提问来源于stack exchange,提问作者George Eden
相关产品推荐
相关产品推荐

