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

Next.js中复用services目录API函数遇data未定义问题如何解决?

问题分析与解决方案

你遇到的错误有两个核心原因:

1. getStaticProps 位置错误

Next.js 的静态生成函数(如 getStaticProps、getServerSideProps)只能在 pages 目录下的页面组件中定义,无法在 components 目录的普通组件中触发执行。你把 getStaticProps 写在 showResult.tsx 里,导致数据根本没有被获取,组件接收的 data 自然是 undefined。

2. API 函数导入方式错误

你的 api.service.ts 中使用的是命名导出(export async function getUserRepos()),但在组件中用了默认导入(import getUserRepos from '../services/api.service'),这会导致 getUserRepos 实际是 undefined,调用时直接失败。


修改后的代码

1. 页面组件 pages/index.tsx

把 getStaticProps 移到页面组件中,获取数据后传递给子组件:

import ShowResult from '../components/showResult'
import { getUserRepos } from '../services/api.service'

// 静态生成函数必须放在页面组件中
export async function getStaticProps() {
  try {
    const data = await getUserRepos();

    if (!data || !Array.isArray(data)) {
      return {
        notFound: true,
      };
    }

    return {
      props: {
        data,
      },
    };
  } catch (error) {
    console.error('获取数据失败:', error);
    return {
      notFound: true,
    };
  }
}

export default function Home({ data }) {
  return (
    <div className='container mx-auto'>      
      <ShowResult data={data} />
    </div>
  );
}

2. 普通组件 components/showResult.tsx

移除无效的 getStaticProps,只保留渲染逻辑:

export default function ShowResult({ data }) {
  return (
    <div className=''>
      <p>Result :</p>
      <ul>
        {data.map((repo) => (
          <li key={repo.id}>{repo.name}</li>
        ))}
      </ul>
    </div>
  )
}

3. API 服务 services/api.service.ts

补充请求错误处理,避免解析无效响应:

export async function getUserRepos() {
  const response = await fetch(
    `https://api.github.com/users/abdurrahmanseyidoglu/repos`
  );
  
  // 检查请求是否成功
  if (!response.ok) {
    throw new Error(`请求失败: ${response.status}`);
  }
  
  const data = await response.json();
  return data;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 02:40:02