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

如何在Next.js页面中传递两个(或多个)API请求的Props?

解决Next.js中合并多个API请求到getServerSideProps的问题

你可以把两个API请求合并到同一个getServerSideProps函数中,通过一次函数执行完成两个接口数据的获取,最终将user和favorites同时作为props传递给页面组件。具体实现如下:

合并后的getServerSideProps代码

export const getServerSideProps = async (context) => {
  const { id } = context.query;
  const backendUrl = process.env.BACKEND_URL;

  // 并行发起两个API请求,提升性能
  const [userRes, favoritesRes] = await Promise.all([
    fetch(`${backendUrl}/User/${id}`),
    fetch(`${backendUrl}/User/${id}/favorites`)
  ]);

  // 解析两个请求的响应数据
  const user = await userRes.json();
  const favorites = await favoritesRes.json();

  return {
    props: { user, favorites }
  };
};

修正后的页面组件代码

注意原组件中favorite.name未用花括号包裹,会直接显示字符串,这里一并修正:

function StartPage({ user, favorites }) {
  return (
    <div>
      <div className={styles.formGroup}>
        <h1>Welcome {user.name}</h1>
      </div>
      <div>
        <h1>These are your favorite movies:</h1>
        {favorites.map(favorite => (
          <div key={favorite.id}>
            <h5>{favorite.name}</h5>
          </div>
        ))}
      </div>
    </div>
  )
}

export default StartPage;

关键说明

  • 使用Promise.all并行发起两个请求,相比串行请求能减少整体等待时间,提升页面加载效率
  • 确保两个接口请求都成功返回后,将数据合并到props对象中返回,页面组件就能同时接收user和favorites两个参数
  • 原代码中的useRouter在getServerSideProps中不需要,因为可以直接通过context.query获取id参数

内容的提问来源于stack exchange,提问作者user16910522

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 17:40:40