将地图中的数据添加到组件列表中

杰克·金特里

我有以下结构的地图。

const myMap = {
    "title1": [
        {
            name: 'one'
        },
        {
            name: 'two'
        },
    ],
    "title2": null,
    "title3": [
        {
            name: 'three'
        },
        {
            name: 'four'
        },
    ],
}

我想将以上内容转换为组件列表,如下所示。

[
    // this array data came from the key title1 as it is first in map
    [
        <MyComponent name={name}/>, // name is 'one'
        <MyComponent name={name}/>, // name is 'two'
    ],
    // this array data came from the key title3 as it is next in map. title2 doesn't show up as its null 
    [
        <MyComponent name={name}/>, // name is 'three'
        <MyComponent name={name}/>, // name is 'four'
    ],
]

我该如何实现?

目前尝试进行以下操作,未按预期显示数据。

<div>
{ myMap && Object.keys(myMap).forEach(key => {
        const array = myMap[key];
        array.forEach(obj => {
            return <MyComponent name={obj.name}/>
        })
    })
}
</div>
阿努拉格·斯里瓦斯塔瓦(Anurag Srivastava)

您也需要在map内部使用map

const myMap = {
    title1: [
      {
        name: "one",
      },
      {
        name: "two",
      },
    ],
    title2: null,
    title3: [
      {
        name: "three",
      },
      {
        name: "four",
      },
    ],
  },
  MyComponent = ({ name }) => <div>{name}</div>,
  generate = (myMap) => {
    return (
      <div>
        {myMap &&
          Object.keys(myMap).map((key) => {
            const array = myMap[key],
              temp =
                array &&
                array.map((obj) => {
                  return <MyComponent name={obj.name} />;
                });

            return (array && <div class="sep">{temp}</div>);
          })}
      </div>
    );
  };

ReactDOM.render(generate(myMap), document.getElementById("root"));
.sep{ outline: 1px solid red; margin: 5px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章