类型错误:无法读取未定义的属性(读取"标题")



我遇到一个奇怪的错误!我试图在我的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}等等给我的错误是" Title "没有定义。另外,如果我试着输入[i],就会出现一个错误&;i&;没有定义!有什么办法吗?提前感谢!

如果body超出循环,则需要为每个条目添加一个键。

<tbody>
{cart.length > 0 && cart.map((item, index) => (             
<tr key={item.id}>
<th scope="row">{index}</th>
<td>{item.title}</td>
<td>{item.code}</td>
<td>{item.quantity}</td>
<td>{item.price}</td>
tr>))}
</tbody>

如果您需要呈现购物车数组中的所有商品,则使用:

{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>}