Next.js中TypeError: products.map is not a function问题求助
解决TypeError: products.map is not a function的问题
我一眼就瞅出问题所在啦!你调用的 https://dummyjson.com/products 接口返回的不是直接的产品数组,而是一个包含products数组的对象。看你代码里的getStaticProps,直接把整个data对象赋值给了products props,导致products变成了一个普通对象——而对象是没有map方法的,这就是报错的根源。
第一步:修正数据传递
修改getStaticProps里的返回值,把data里的products数组提取出来传给props:
export async function getStaticProps() { const response = await fetch("https://dummyjson.com/products"); const data = await response.json(); console.log(data); // 你可以在控制台看到data结构:{products: [...], total: ...} return { props: { products: data.products, // 这里改成data.products,拿到真正的数组 }, }; }
第二步:添加安全校验(可选但推荐)
为了避免后续可能出现的类似问题,建议在调用map之前先判断products是否为数组:
{Array.isArray(products) && products.map((product) => { return ( <div key={product.id}> <Link href={`/product/${product.id}`}> {/* 这里可以补全产品详情页的链接 */} <h2> {product.id} {product.title} </h2> </Link> </div> ); })}
简单说,dummyjson的/products接口返回的数据结构是这样的:
{ "products": [{"id":1,"title":"iPhone 9",...}, ...], "total": 100, "skip": 0, "limit": 30 }
你之前拿的是整个外层对象,现在要拿里面的products数组就对啦!
内容的提问来源于stack exchange,提问作者user19988646
相关产品推荐
相关产品推荐

