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

Next.js 13无法使用GetStaticProps及数据获取报错求助

问题分析与解决方案

错误根源

出现Cannot read properties of undefined (reading 'slice')的原因有两个:

  • Next.js 13 App Router 不支持getData函数,你导出的getData不会被框架识别,导致组件接收不到resources props,最终resources为undefined。
  • 请求URL存在语法错误:'http://localhost:3000/api/resources"'末尾多了一个双引号,导致请求地址无效,无法正确获取数据。

修正方案

App Router 中,默认组件是Server Component,可直接在组件内部通过async/await获取数据,无需额外导出数据获取函数。修正后的代码如下:

import Layout from "components/Layout.js";
import ResourceHighlight from "components/ResourceHighlight.js";
import ResourceList from "components/ResourceList.js";
import Newsletter from "components/Newsletter.js";
import Footer from "components/Footer.js";

async function Home() {
  // 修正URL的引号错误
  const res = await fetch('http://localhost:3000/api/resources');
  
  // 检查请求是否成功,避免无效响应导致解析失败
  if (!res.ok) {
    throw new Error('获取资源数据失败');
  }
  
  const resources = await res.json();

  return ( 
    <Layout> 
     <ResourceHighlight
        resources={resources.slice(0,2)}
      />
      <ResourceList
        resources={resources.slice(2)}
      />
       <Newsletter /> 
      <Footer />
    </Layout>
  )
}

export default Home; 

额外说明

  • 若需要实现原getStaticProps的静态生成效果,App Router 默认会对无动态参数的页面进行静态生成,无需额外配置。
  • 添加请求状态检查(!res.ok)可以在接口异常时抛出明确错误,便于排查问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 15:07:35