【问题标题】:React Map Array of Object with Nested Object [duplicate]React Map Array of Object with Nested Object [重复]
【发布时间】:2022-12-06 23:54:49
【问题描述】:

在反应中,我想显示类别的 ID 和名称。假设下面的对象如何实现这一点对我来说有点难以理解。

[
    {
        "id": 1,
        "category": {
            "id": 1,
            "name": "CALZATURA",
        }
    },
    {
        "id": 2,
        "category": {
            "id": 2,
            "name": "PELLETTERIA",
        }
    }
]
dataItems.map((item, index) => {
  return (
    <div>
      <h1>{item.title}</h1>
      {category.map((c, i) => (
        <div>
          <p>{c.name}</p>
        </div>
      ))}
    </div>
  );
});

【问题讨论】:

  • 你尝试了什么,什么没有按预期工作?通常,人们会在 React 渲染函数中使用 .map() 来输出数组中的元素。问题的标题暗示你已经知道了。那么你被困在哪里了?
  • dataItems.map((item, index) => { return ( <div> <h1>{item.title}</h1> { category.map((c, i) => <div> <p>{c.名称</p> </div>)} </div> ) })
  • 相关代码属于问题,不属于cmets。请更新问题以包括您的尝试并具体描述未按预期工作的内容。 (一眼看去,该注释中的代码应该会失败,因为您正在尝试使用一个名为 category 的变量,该变量从未定义过。)

标签: javascript


【解决方案1】:

假设您的数组存储在名为const categories = [...]; 的变量中。

return (
  <div>
    {categories.map((category) => (
      <div>
        <span>{category.id}</span>
        <span>{category.category.name}</span>
      </div>
    )}
  </div>
)

【讨论】:

    猜你喜欢
    • 2022-12-01
    • 2022-12-01
    • 2022-12-01
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    • 2022-12-02
    • 1970-01-01
    相关资源
    最近更新 更多