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

Reactjs中如何调用两个API获取产品数据及对应商品图片

实现方案

方案1:父组件批量获取图片后合并数据(适合产品数量较少的场景)

拿到产品列表后,并发请求所有产品的图片资源,合并到产品数据中再统一渲染:

import axios from "axios";
import {  useEffect, useState } from "react";
import { SingleContent } from "../../components/SingleContent/SingleContent";

export const All = () => {
    const [content, setContent] = useState([]);
    // 复用请求配置,避免重复编写
    const requestConfig = {
        headers: {
            "api-auth-accountid": process.env.REACT_APP_API_ID,
            "api-auth-applicationkey": process.env.REACT_APP_API_KEY
        }
    }
  
    const fetchAllProducts = async () => {
        try {
            // 1. 获取产品列表
            const  { data } = await axios.get('https://inventory.dearsystems.com/ExternalApi/v2/Product', requestConfig);
            const productList = data.Products || [];

            // 2. 批量请求每个产品的图片
            const productWithImgPromises = productList.map(async (product) => {
                try {
                    const imgRes = await axios.get(`https://inventory.dearsystems.com/ExternalApi/v2/product/attachments?ProductID=${product.ID}`, requestConfig);
                    // 假设接口返回的附件列表第一个是商品主图,可根据实际返回结构调整
                    const mainImg = imgRes.data?.[0]?.DownloadUrl || '';
                    return { ...product, mainImg }
                } catch (e) {
                    // 单个图片请求失败不影响整体渲染,返回默认空图或者占位图地址即可
                    return { ...product, mainImg: '' }
                }
            })

            // 3. 等待所有图片请求完成后更新状态
            const productWithImg = await Promise.all(productWithImgPromises);
            setContent(productWithImg)
        } catch (e) {
            console.error('产品列表获取失败', e)
        }
    }
   
    useEffect(() =>{
        fetchAllProducts();
    }, [])

    return (
        <div>
            <h1 className="pageTitle">All Products</h1>
            <div className="all">
                {content.map((c) => 
                    <SingleContent 
                        key={c.ID} 
                        id={c.ID} 
                        name={c.Name} 
                        sku={c.SKU} 
                        category={c.Category}
                        mainImg={c.mainImg}
                    /> 
                )}
            </div>
        </div>
    )
}

后续只需在SingleContent组件中接收mainImg属性,放到img标签的src属性渲染即可。

方案2:子组件内部请求图片(适合产品数量较多的场景)

如果产品数量多,父组件一次性发起大量请求容易触发接口限流,可把图片请求逻辑放到SingleContent内部实现,还可以方便添加加载中占位、加载失败兜底逻辑,示例代码:

// SingleContent 组件示例
import axios from "axios";
import { useEffect, useState } from "react";

export const SingleContent = (props) => {
    const { id, name, sku, category } = props;
    const [mainImg, setMainImg] = useState('');
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const fetchImg = async () => {
            setLoading(true);
            try {
                const res = await axios.get(`https://inventory.dearsystems.com/ExternalApi/v2/product/attachments?ProductID=${id}`, {
                    headers: {
                        "api-auth-accountid": process.env.REACT_APP_API_ID,
                        "api-auth-applicationkey": process.env.REACT_APP_API_KEY
                    }
                })
                setMainImg(res.data?.[0]?.DownloadUrl || '')
            } catch (e) {
                setMainImg('你的自定义占位图地址')
            } finally {
                setLoading(false)
            }
        }
        fetchImg();
    }, [id])

    return <div className="single-product">
        {loading ? <div>图片加载中</div> : <img src={mainImg} alt={name} />}
        <h3>{name}</h3>
        <p>SKU: {sku}</p>
        <p>分类: {category}</p>
    </div>
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 21:27:03