首页 > 解决方案 > TypeError:无法读取未定义的属性(读取“标题”)

问题描述

我面临一个奇怪的错误!我正在尝试在我的 UI 上动态呈现产品。当我的代码中有:

 render () {
    const cart = this.props.cart
    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>
                  {cart.length > 0 && 
                    <tbody>
                    <tr>
                      <th scope="row">1</th>
                      <td>{cart[0].title}</td>
                      <td>{cart[0].code}</td>
                      <td>{cart[0].quantity}</td>
                      <td>{cart[0].price}</td>
                    </tr>
                    </tbody>}
                </table>
              </CardBody>
            </Card>
          </Col>
        </Row>
      </div>
    </>
    )
  }
}

它呈现第一个项目,但是如果我尝试选择第三个项目:即 {cart[2].title} 等等会给我“标题”未定义的错误。另外,如果我尝试给 [i] 给我一个“i”未定义的错误!任何想法如何解决它?先感谢您!

标签: javascriptreactjsredux

解决方案


如果您需要渲染购物车数组中的所有商品,请使用:

              {cart.map(c =>  
                <tbody>
                <tr>
                  <th scope="row">1</th>
                  <td>{c.title}</td>
                  <td>{c.code}</td>
                  <td>{c.quantity}</td>
                  <td>{c.price}</td>
                </tr>
                </tbody>}

推荐阅读