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

React动态渲染购物车列表报Cannot read properties of undefined问题咨询

错误原因
  • 访问cart[2].title报错:数组索引从0开始计数,当你的cart数组长度不足3时,cart[2]的值为undefined,读取undefined的title属性就会触发TypeError。
  • 使用cart[i].title提示i未定义:你没有在当前作用域声明变量i,也没有通过循环逻辑生成遍历用的下标。
解决方法

你需要用数组map方法动态遍历渲染所有商品,这是React中渲染列表的标准实现,改写后的代码如下:

render () {
    const cart = this.props.cart || [] // 兜底防止cart是undefined
    return (
      <>
        <PanelHeader size="sm" />
        <div className="content">
          <Row>
            <Col xs={12}>
              <Card>
                <CardHeader>
                  <CardTitle tag="h4">Products List</CardTitle>
                </CardHeader>
                <CardBody>
                <table class="table table-striped table-hover">
                  <thead>
                    <tr>
                      <th scope="col"><strong>#</strong></th>
                      <th scope="col"><strong>Name</strong></th>
                      <th scope="col"><strong>Code Item</strong></th>
                      <th scope="col"><strong>Quantity</strong></th>
                      <th scope="col"><strong>Price Total</strong></th>
                    </tr>
                  </thead>
                  <tbody>
                    {cart.map((item, index) => (
                      <tr key={item.id || index}> {/* 优先用商品唯一id作为key,无唯一值时可暂用索引 */}
                        <th scope="row">{index + 1}</th>
                        <td>{item?.title}</td> {/* 可选链兜底,避免单条数据异常时报错 */}
                        <td>{item?.code}</td>
                        <td>{item?.quantity}</td>
                        <td>{item?.price}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </CardBody>
            </Card>
          </Col>
        </Row>
      </div>
    </>
    )
  }
}
补充说明

如果确实需要单独访问某一个下标的商品属性,可使用可选链操作符兜底,比如:
{cart[2]?.title}
这种写法下就算cart[2]不存在,只会返回undefined,不会抛出阻断渲染的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:48:04