簡體   English   中英

為對象中的每個元素渲染為DOM

[英]Rendering into DOM for each element in object

我有一個JS對象,里面裝有嵌套的對象。 如果您希望獲得詳細信息,它是我的投資組合的“項目”對象,其中有7個項目,每個項目都有標題,描述,詳細信息和圖像URL。 它是這樣設置的:

const projects = {
  0: {
    title: "Project name",
    description:
      "A cool description",
    details: [
      "First detail",
      "Second point",
      "Third item"
    ].map(detail => <li>{detail}</li>),
    image: "image_url"
  },
  1: { ... },
  2: { ... },
  ...

現在,基於此數據,我想將每個項目的一個div元素呈現到DOM中,這似乎效果不佳。 我嘗試了多種方法,最終我可以將'projects'常量作為道具傳遞到我需要的地方,但是由於它是一個Object而不是數組,因此我似乎無法在map上使用map方法它(您可以看到我使用了該方法來呈現列表項)。

這是我目前正在嘗試的方法:

function ProjectList(props) {
  const projects = props.projects;
  const projectItems = projects.map(project => <h1>Test</h1>);

  return <ul>{projectItems}</ul>;
}

然后進入渲染功能...

<ProjectList projects={projects} />

期望:7個h1標簽說“測試”(如果可以渲染,我可以從那里拿走)

好消息:ProjectList中的項目常量確實返回了適當的對象。

壞消息: “ projects.map不是函數”

因此,基本上我想我要問的是一種有效地迭代嵌套對象並每次將元素呈現到DOM中的方法。 很抱歉,這是一件非常基本的事情,但這是我的第一個反應項目,我已經盡力了。

非常感謝您的幫助!

如其他人所述,您不能映射對象,但是可以使用來映射對象的鍵

Object.keys(projects).map( key => <h1>{projects[key].title}</h1>)

由於您正在為項目對象使用基於整數的鍵,因此最好將其聲明為如下數組:

const projects = [
    {
        title: "Project name",
        description: "A cool description",
        details: [
            "First detail",
            "Second point",
            "Third item"
        ].map(detail => <li>{detail}</li>),
        image: "image_url"
    },
    { ... },
    { ... }
]

那你就可以用

projects.map(project => <h1>Test</h1>);

如果由於某種原因需要元素的索引,可以使用

projects.map((project, index) => <h1>Project {project.title} is index {index}</h1>);

最大的問題是項目是一個對象,因此沒有地圖數組功能。 也許這個例子會很有用。

使用Objecj作為數組使用React的示例地圖

const projects = {
  0: {
    title: "Project name",
    description:
      "A cool description",
    details: [
      "First detail",
      "Second point",
      "Third item"
    ],
    image: "image_url"
  },
  1: {
    title: "Project name 2",
    description:
      "A cool description",
    details: [
      "First detail",
      "Second point",
      "Third item"
    ],
    image: "image_url"
  }
};

function ProjectItem(props) {
  return (
    <li>{props.item.title}</li>
  );
}


function ProjectList () {

  const newProjects = Object.values(projects);
  console.log('teste',newProjects);

  return (
    <ul>
      {newProjects.map(item =>
        <ProjectItem key={item.title} item={item} />
       )}
    </ul>
  );
}

// ========================================

ReactDOM.render(
  <ProjectList />,
  document.getElementById('root')
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM