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

Next.js 13 App Dir中如何获取商品接口返回的首张图片?

Next.js 13 App Dir中提取Django API商品首张图片的解决方案

API返回数据格式

{"count": 1000,"next": "http://127.0.0.1:8000/store/products/?page=2","previous": null,"results": [{"id": 648,"title": "7up Diet, 355 Ml","slug": "-","description": "tincidunt eget tempus vel pede morbi porttitor lorem id ligula suspendisse ornare consequat lectus in est","inventory": 82,"unit_price": 79.07,"price_with_tax": 86.977,"collection": 5,"images": [{"id": 1,"image": "http://127.0.0.1:8000/media/store/images/joan-tran-reEySFadyJQ-unsplash.jpg"},{"id": 4,"image": "http://127.0.0.1:8000/media/store/images/grant-ritchie-n_wXNttWVGs-unsplash_uJitfkC.jpg"}]}]}

当前代码问题

你当前代码中尝试通过item.image获取图片,但API返回的商品图片数据存储在images数组中,不存在image字段,因此无法正确加载图片。

解决方案

从每个商品的images数组中提取第一个元素的image属性即可。为了避免数组为空时出现报错,使用**可选链操作符?.**做安全访问,还可以添加默认图片地址作为降级处理。

修正后的完整代码

import Image from 'next/image';
import Link from 'next/link';

export default async function ProductsAll() {
  const response = await fetch('http://127.0.0.1:8000/store/products/');
  const { results } = await response.json();

  return (
    <>
      <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3 p-4">
        {results?.map((item: any) => (
          <div key={item.id} className="card card-compact bg-base-100 h-80 shadow-xl">
            <figure>
              {/* 核心修改:从images数组取首张图片,添加可选链处理空值 */}
              <Image 
                height={500} 
                width={500} 
                src={item.images?.[0]?.image || '/default-product-image.jpg'} 
                alt={item.title} 
              />
            </figure>
            <div className="card-body">
              <h2 className="card-title truncate hover:text-clip">{item.title}</h2>
              <p className="truncate hover:text-clip">{item.description}</p>
              <div className="card-actions justify-end">
                <button className="btn btn-outline btn-accent md:btn-md">
                  <Link href={item.slug}>Buy Now</Link>
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </>
  )
}

关键修改说明

  • item.images?.[0]?.image:通过可选链安全访问数组第一个元素的image字段,当images数组为空或不存在时,表达式返回undefined
  • || '/default-product-image.jpg':可选添加,当没有图片时显示默认图,需要在项目public目录下放对应图片

内容的提问来源于stack exchange,提问作者Sabbir Hasan Munna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 20:03:20