我正在尝试遍历对象数组,在divs中显示结果,但是某些操作没有按预期进行。当我控制台日志时,似乎正在检索数据并显示它。
const example =
{
"example": [
{
"test": "test",
"img": "img.png",
"song": "song title"
},
{
"test": "test2",
"img": "img.png2",
"song": "song title2"
}
]
}
const renderData= () => {
example.example.forEach(function (arrayItem) {
const test= arrayItem.test
const img= arrayItem.img
const song= arrayItem.song
return (
<div className="test">
<div className="test">
<div className="test">
<img
src={img}
alt="sunil"
/>
</div>
<div className="test">
{test}
<span className="test">
</span>
<p>{song}</p>
</div>
</div>
</div>
);
});
};
return (
<div
{renderData()}
</div>
);
}
什么都没有出现,但是当我这样做时:
example.example.forEach(function (arrayItem) {
var x = arrayItem.test+ arrayItem.img+ arrayItem.song;
console.log(x);
});
它可以工作并管理正确的信息。
有人能发现错误或帮忙吗?
请忽略命名约定。
答案 0 :(得分:3)
您需要从JSX.Element
返回renderData
的数组。对于您的情况,您返回undefined
。返回带有map的JSX.Element
的新数组,而不是forEach,该数组不返回任何内容。
const renderData = () => {
return example.example.map((arrayItem, i) => {
const test = arrayItem.test;
const img = arrayItem.img;
const song = arrayItem.song;
return (
<div key={i} className="test">
<div className="test">
<div className="test">
<img src={img} alt="sunil" />
</div>
<div className="test">
{test}
<span className="test"></span>
<p>{song}</p>
</div>
</div>
</div>
);
});
};