NextJS如何通过路由ID调用API并渲染用户数据?
问题修复方案
核心错误点
- 函数名拼写错误:
getServerSidePros应为getServerSideProps(Next.js 官方规定的服务端渲染函数名) - getServerSideProps 参数错误:该函数接收的是
context对象,不是直接的id,需从context.query中提取查询参数 - 冗余函数未使用:自定义的
GetQuery函数在服务端渲染场景下完全不需要,直接通过context获取参数即可 - 接口路径不匹配:你描述的接口是
/Users/{id},但代码中写的是/User/${id},需和后端接口路径保持一致 - 组件 props 访问错误:组件接收的是包含数据的 props 对象,需正确解构或访问内部属性
修正后的完整代码
// 服务端渲染函数:正确获取查询参数并请求接口 export const getServerSideProps = async (context) => { // 从 context.query 中提取地址栏的 id 参数 const id = context.query.id; // 检查 id 是否存在,避免无效请求 if (!id) { return { redirect: { destination: '/', // 无 id 时重定向到首页或其他页面 permanent: false, }, }; } // 请求后端接口,注意路径和你描述的保持一致 const res = await fetch(`${process.env.BACKEND_URL}/Users/${id}`); const userData = await res.json(); return { props: { user: userData }, // 将用户数据传递给页面组件 }; }; // 页面组件:正确接收并渲染用户数据 const UserPage = ({ user }) => { return ( <div> <h1>Hello</h1> {/* 用可选链避免数据未加载时报错 */} <h1>{user?.name || '用户信息未加载'}</h1> </div> ); }; export default UserPage;
额外说明
- 服务端渲染场景下优先用
getServerSideProps的context参数获取查询参数,比客户端用useRouter更高效,还能避免 hydration 不匹配问题 - 添加
id存在性检查,防止地址栏无id时发起无效请求 - 使用
user?.name可选链操作符,避免用户数据未返回或结构异常时页面崩溃
内容的提问来源于stack exchange,提问作者user16910522
相关产品推荐
相关产品推荐

