使用ES6 / React分解简单的嵌套对象

问题描述 投票:-1回答:1

我有这个对象

const launch = {
    "flight_number": 102,
    "mission_name": "GPS SV05",
    "mission_id": []
    "rocket": {
        "rocket_id": "falcon9",
        "rocket_name": "Falcon 9",
        },
    "details": null,
    "upcoming": true,
    "static_fire_date_utc": null,
    "static_fire_date_unix": null,
    "timeline": null,
    "crew": null
}

如何从此obj获取rocket_name?我尝试过这样的解构

const {rocket: {rocket_name}} = launch

然后尝试获取

{rocket_name}

在我的JSX中,但返回了TypeError:launch.rocket未定义

const launch = {
  "flight_number": 102,
  "mission_name": "GPS SV05",
  "mission_id": []
  "rocket": {
    "rocket_id": "falcon9",
    "rocket_name": "Falcon 9",
  },
  "details": null,
  "upcoming": true,
  "static_fire_date_utc": null,
  "static_fire_date_unix": null,
  "timeline": null,
  "crew": null
}

const {
  rocket: {
    rocket_name
  }
} = launch

我尝试了许多不同的方法来破坏它的结构,即使这样做launch.rocket.rocket_name

并且react仍然返回相同的错误。

javascript reactjs object ecmascript-6 destructuring
1个回答
2
投票

听起来像您的情况,其中一个或多个记录没有设置rocket属性。您可以通过提供默认值来缓解这种情况,例如

const {rocket: {rocket_name} = {}} = launch
© www.soinside.com 2019 - 2024. All rights reserved.