我有以下结构的地图。
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>
您也需要在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] 删除。
我来说两句