TypeError: Cannot read property 'map' of undefined state object inside array?

TypeError: Cannot read property 'map' of undefined state object inside array?

数组中的状态对象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
    }
    }

when 在状态对象数组中循环

{this.state.order.order_trans.map((p) => (
                    <p>{p.id}</p>
                ))}

我收到错误类型错误:无法读取未定义的 属性 'map'

我认为你是在渲染后更新状态。在这种情况下,只需确保 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>
            ))}