[英]How can I render out the items in my array one at a time when returning them?
I have an array of objects.我有一个对象数组。
Each object has a few strings and an array of strings.每个对象都有几个字符串和一个字符串数组。
I want to render out the array of strings part of the object with an unordered list.我想用无序列表渲染出对象的字符串数组。
Right now I'm using:现在我正在使用:
const renderOut = this.props.data.filter(obj => {
return this.state.keyToFind.includes(obj.name);
}).map((obj, idx) => {
return (
<div key={idx}>
<h2>{obj.name}</h2>
<ul>
<li>{obj.arrayItems}</li>
</ul>
</div>
);
});
The problem with the code above is that it renders out obj.arrayItems all in a row.上面代码的问题在于它连续渲染了 obj.arrayItems。 For example...例如...
[ "cup", "ball", "toy" ] [“杯子”、“球”、“玩具”]
renders out as....呈现为....
cupballtoy杯子玩具
but I'm trying to get it to look like:但我试图让它看起来像:
Is there a way I can render out obj.arrayItems one at a time?有没有办法一次渲染一个 obj.arrayItems ?
You can use a nested map function.您可以使用嵌套映射函数。
const renderOut = this.props.data.filter(obj => {
return this.state.keyToFind.includes(obj.name);
}).map((obj, idx) => {
return (
<div key={idx}>
<h2>{obj.name}</h2>
<ul>
{obj.arrayItems.map(item => <li key={item}>{item}</li>)}
</ul>
</div>
);
});
Yes, create a map function to return the strings into DOM elements inside the ul.是的,创建一个 map 函数将字符串返回到 ul 中的 DOM 元素中。 React does require a unique key prop to help keep track of these components, but for simplicity, in this case, you can use the array index. React 确实需要一个唯一的 key prop 来帮助跟踪这些组件,但为了简单起见,在这种情况下,您可以使用数组索引。
{ obj.arrayItems.map( (item, i) => <li key={i} >{ item }</li> ) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.