You need to enable JavaScript to run this app. React.js开发电商站ProductDetail组件调用Mock API出现undefined报错修复
优惠活动
大模型
产品
解决方案
定价
更多

React.js开发电商站ProductDetail组件调用Mock API出现undefined报错修复

核心Bug定位

  • 接口返回的dress是全量商品数组,后续执行dress.map(...)得到的data依然是数组结构,并非单个商品对象。
  • 弹窗中直接调用data.name、data.price、data.description取值,本质是在数组上读取对象属性,所有取值自然返回undefined。
  • 逻辑缺失关键步骤:没有根据当前要展示的目标商品id,从全量列表中筛选出对应单条数据,没有把数组转换为弹窗需要的单个商品数据源。
  • 从props中解构出的id、name等字段完全没有参与业务逻辑,属于无效代码。

分步修复方案

  1. 调整数据取值逻辑
    不要把遍历全量列表得到的数组直接当单商品使用,拿到全量接口数据后,结合父组件传入的目标商品id,筛选出弹窗需要展示的单条商品:
    // 从props获取父组件传入的目标商品id
    const { productId, buttonLabel, className } = props;
    const axios = require('axios');
    const [modal, setModal] = useState(false);
    const [dress, setDress] = useState([]);
    const toggle = () => setModal(!modal);
    
    useEffect(() => {
        axios
            .get(`https://5fd9d76f6cf2e7001737ead3.mockapi.io/api/v1/dress`)
            .then(res => setDress(res.data))
            .catch(err => console.log(err));
    }, []);
    
    // 从全量列表中匹配对应id的单条商品,空值兜底为空对象避免取值报错
    const currentProduct = dress.find(item => item.id === productId) || {};
    
  2. 替换弹窗内的错误取值
    把原代码中所有data.xxx的取值,全部替换为从单条商品对象currentProduct上读取:
    <Modal isOpen={modal} toggle={toggle} key={currentProduct.id} className={className}>
        <ModalHeader toggle={toggle}>{currentProduct.name}</ModalHeader>
        <ModalBody>{currentProduct.price}</ModalBody>
        <ModalBody>{currentProduct.description}</ModalBody>
        <ModalFooter>
            <Button color="secondary" onClick={toggle}>
                Kapat
            </Button>
        </ModalFooter>
    </Modal>
    
  3. 补充异步加载兜底
    因为接口请求是异步过程,首次渲染时currentProduct可能是空对象,可以在弹窗内加简单的加载占位,当Object.keys(currentProduct).length === 0时展示“加载中”提示,避免用户看到空白内容。

可优化点

  • 每个ProductDetail组件单独请求一次全量列表接口属于重复性能浪费,可将列表请求逻辑上移到父组件,把单个商品数据通过props传递给Detail组件,无需每个弹窗重复调用相同接口。
  • 项目内可将require('axios')改为文件顶部统一import axios from 'axios',符合现代React项目的代码规范。
  • JSX中不需要用字符串模板`${data.xxx}`包裹变量,直接用花括号插值即可,套字符串模板反而容易将undefined直接渲染为页面文本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.12 21:54:01