我有一个 React 组件,其功能可呈现音乐制作列表。 titles
是一个字符串对象并且 props.current.credits
是一个数组对象(它们是从更大的 JSON 中提取的,因此无法更改数据结构)。
const titles = {
featuring: "Featuring",
recorded: "Recorded at",
samples: "Samples",
...etc
}
props.current.credits = {
"writers": ["John Doe", "Sally Singer"],
"recorded": [{
"studio": "ABC Studios",
"city": "Houston, Texas"
}],
...etc
}
该函数仅渲染 h2
标签,但不是 p
forEach
内的标签代码块。当我测试forEach
时通过记录阻止 name
到控制台时,会出现这些值,所以我完全不知道问题可能是什么。对此有一些见解将不胜感激。
const Credit = props => {
const credit = type => {
if (props.current.credits.hasOwnProperty(type)) {
if (type === "recorded") {
return (
<div className="credit">
<h2>{titles[type]}</h2>
{
props.current.credits[type].forEach(name => {
return (
<p className="location">
<span className="studio">{name.studio}</span>
<span className="city">{name.city}</span>
</p>
)
})
}
</div>
)
}
if (type === "samples" || type === "interpolates") {
return (
<div className="credit">
<h2>{titles[type]}</h2>
{
props.current.credits[type].forEach(name => {
return (
<p className="location">
<span className="studio">{name.title}</span>
<span className="city">{{ __html: name.info }}</span>
</p>
)
})
}
</div>
)
}
return (
<div className="credit">
<h2>{titles[type]}</h2>
{
props.current.credits[type].forEach(name => {
return (
<p>{name}</p>
)
})
}
</div>
)
}
return null;
}
return (
<div>
{credit("samples")}
</div>
)
}
最佳答案
根据官方文档,you should use map
.
所以一个例子是:
{
props.current.credits[type].map((name) => {
return (
<p className="location">
<span className="studio">{name.studio}</span>
<span className="city">{name.city}</span>
</p>
);
});
}
关于javascript - React forEach 函数不渲染 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72678812/