数组order_trans中的状态对象映射错误
this.state = {
order: {
"id": 2,
"order_trans": [
{
"id": 2,
"order_payment_id": "61023184-4ee7-4b8d-80c7-b593b994607f",
"order_amount": 11628.0,
"signature": "TSbSYzqNcT3PD7sgu4KGpuTsgIPzumTeg753iswBGsw=",
"created_at": "2020-10-29T16:13:22.158603Z",
"updated_at": "2020-10-29T16:13:22.158630Z",
"buyer": 20,
"order": 2
}
],
"order_token": "61023184-4ee7-4b8d-80c7-b593b994607f",
"grand_total": 11628.0,
"name": "Achu",
"land_mark": "",
"created_at": "2020-10-29T16:12:31.291014Z",
"updated_at": "2020-10-29T16:12:31.291035Z",
"buyer": 20
}
}
在状态对象数组中循环时
{this.state.order.order_trans.map((p) => (
<p>{p.id}</p>
))}
我收到错误TypeError:无法读取未定义的属性“地图”
答案 0 :(得分:0)
我认为您正在渲染后更新状态。在这种情况下,只需确保状态中存在order_trans
值。您可以执行以下操作,
{this.state.order && this.state.order.order_trans && this.state.order.order_trans.map((p) => (
<p>{p.id}</p>
))}
或者您可以使用新的可选链接运算符,
{ this.state.order?.order_trans.map((p) => (
<p>{p.id}</p>
))}