Next.js中getStaticProps返回Undefined问题求助
问题分析与解决方案
你的问题主要出在三个核心点:API数据结构处理错误、缺少请求异常处理、组件map逻辑不规范,最终导致info或map返回值为undefined。
1. API返回数据结构不符预期
你调用的https://links.papareact.com/pyp返回的是包含results数组的对象,而非直接的数组。原代码直接把整个data对象传给info,导致info是对象而非数组,没有map方法,组件渲染时触发异常,最终info被处理为undefined。
2. 缺少请求错误处理
原getStaticProps没有处理请求失败的情况(比如网络错误、API返回非200状态码),一旦请求出错,data会是undefined,进而导致info为undefined。
3. 组件map逻辑无返回值
你的map回调里只有console.log(item),没有返回JSX元素,map会生成一个全是undefined的数组,终端因此输出这些undefined。
修复后的getStaticProps代码
export async function getStaticProps() { try { const res = await fetch("https://links.papareact.com/pyp"); // 校验请求是否成功 if (!res.ok) { throw new Error(`请求失败,状态码:${res.status}`); } const data = await res.json(); // 校验数据结构是否符合预期 if (!data?.results || !Array.isArray(data.results)) { throw new Error("API返回数据结构不符合预期"); } return { props: { info: data.results // 传递正确的数组数据 } }; } catch (error) { console.error("获取数据失败:", error); // 返回空数组避免组件崩溃 return { props: { info: [] } }; } }
修复后的组件代码
export default function Home({ info = [] }) { return ( <div> <Header/> <Banner/> <main className='max-w-7xl mx-auto px-8 sm:px-16' > <section> <h2 className='text-4xl font-semibold pb-5 pt-6'>Explore NearBy</h2> {/* 先校验info是否为数组,再执行map */} {Array.isArray(info) ? info.map((item, index) => { console.log(item); // 必须返回JSX元素,否则map会生成undefined数组 return <div key={index}>{item.name}</div>; }) : <p>暂无数据</p>} </section> </main> </div> ); }
内容的提问来源于stack exchange,提问作者Abdessalam Semlali
相关产品推荐
相关产品推荐

