按键分组的React js中的渲染对象

时间:2018-03-12 15:29:44

标签: javascript reactjs

我的数据结构如下:

{
  oldPics: {
    [title: 'dog', url: 'www.dog.com'],
    [title: 'cat', url: 'www.cat.com'],
    [title: 'bird', url: 'www.bird.com'],
  },

  newPics: {
    [title: 'fox', url: 'www.fox.com'],
    [title: 'lion', url: 'www.lion.com'],
  },

  archivedPics: {
    [title: 'eagle', url: 'www.eagle.com'],
    [title: 'fish', url: 'www.fish.com'],
    [title: 'monkey', url: 'www.monkey.com'],
  },
}

我想显示如下数据:

<div>
  <div>
    <h3>old</h3>
    <p>title: dog, url: www.dog.com</p>
    <p>title: cat, url: www.cat.com</p>
    <p>title: bird, url: www.bird.com</p>
  </div>


  <div>
    <h3>new</h3>
    <p>title: fox, url: www.fox.com</p>
    <p>title: lion, url: www.lion.com</p>
  </div>

  <div>
    <h3>archived</h3>
    <p>title: eagle, url: www.eagle.com</p>
    <p>title: fish, url: www.fish.com</p>
    <p>title: monkey, url: www.monkey.com</p>
  </div>
</div>

我已尝试在我的组件中按如下方式呈现它,但它呈现空的<div>元素:

  _renderPics(group) {

    const content = []

    const piccies = Object
                    .keys(group)
                    .map(key => content.push(
                        <div key={key}>title: {group[key].title} url: {group[key].url}</div>
                    ));
    return content

  }

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

假设您的数据结构在您的实际案例中是正确的,那么两个嵌套的地图应该完成这项工作:

_renderPics(group) {
  return Object
    .keys(group)
    .map((key, index) => (
      <div key={index}>
        <h3>{key.replace('Pics', '')}</h3>
        {group[key].map((pic, i) => (
          <div key={i}>title: {pic.title}, url: {pic.url}</div>
        ))}
      </div>
    ));
}

演示: https://codesandbox.io/s/l94mml0yj9

答案 1 :(得分:1)

您必须从

更正数据结构
oldPics: {
 [title: 'dog', url: 'www.dog.com'],
 [title: 'cat', url: 'www.cat.com'],
 [title: 'bird', url: 'www.bird.com'],
}

oldPics: [
 {title: 'dog', url: 'www.dog.com'},
 {title: 'cat', url: 'www.cat.com'},
 {title: 'bird', url: 'www.bird.com'},
]

然后

{Object.keys(group).map((key, y) =>
  <div key={y}>
    <h3>{key.replace('Pics', '')}</h3>
      {group[key].map((item, y) =>
      <div key={y}>title: {item.title} url: {item.url}</div>
      )}
  </div>
)}

https://codesandbox.io/s/1r3mp5jnj4