You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS如何通过路由ID调用API并渲染用户数据?

问题修复方案

核心错误点

  1. 函数名拼写错误:getServerSidePros 应为 getServerSideProps(Next.js 官方规定的服务端渲染函数名)
  2. getServerSideProps 参数错误:该函数接收的是 context 对象,不是直接的 id,需从 context.query 中提取查询参数
  3. 冗余函数未使用:自定义的 GetQuery 函数在服务端渲染场景下完全不需要,直接通过 context 获取参数即可
  4. 接口路径不匹配:你描述的接口是 /Users/{id},但代码中写的是 /User/${id},需和后端接口路径保持一致
  5. 组件 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:09:24