【问题标题】:Destructuring simple nested Object with ES6/React [closed]使用 ES6/React 解构简单的嵌套对象 [关闭]
【发布时间】:2020-04-26 13:45:43
【问题描述】:

我有这个对象

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 is undefined

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 仍然返回相同的错误。

【问题讨论】:

  • 你能分享你的代码吗?只有渲染功能。
  • 您的语法当前无效。修复它,它对我来说运行良好
  • "mission_id": []之后有一个 ,

标签: javascript reactjs object ecmascript-6 destructuring


【解决方案1】:

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

const {rocket: {rocket_name} = {}} = launch

【讨论】:

    猜你喜欢
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 2020-08-12
    • 2020-04-02
    相关资源
    最近更新 更多