简体   繁体   English

如何在返回数组时一次渲染一个项目?

[英]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:但我试图让它看起来像:

  • cup杯子
  • ball
  • toy玩具

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.

相关问题 如何将组件存储在数组中并在需要时在 React 中渲染它们? - How to store components in an array and render them when I need in React? 如何在不卸载它们的情况下渲染一组组件? - How can I render an array of components in react without them unmounting? 当我的搜索字段为空时,如何显示没有结果的页面,但搜索时仍然异步显示? - How can I render out to page no results when my search field is empty, but still render asynchronously when searching? 当用户注销其中一个选项卡时,如何自动从所有打开的选项卡中注销用户? - How can I logout a user from all open tabs automatically when user logs out in one of them? 如何将数组中的项目与对象中的项目匹配? - How can I match items in my array with items in my object? javascript:将项目从一个数组中取出并放入另一个数组中 - javascript: pulling items out of one array and putting them in another 如何在删除其中一个项目时重新编号? - How to renumber items when one of them is removed? 如何使用javascript中的for循环列出数组中的项目? - How can I list out items in an array using a for loop in javascript? 如何将数组项一一添加到DOM? - How can I add array items to DOM one by one? 如何从一个数组中提取数组并将它们转换为对象并将它们放入一个新数组中? - how can i extract arrays from one array & convert them in object and put them in a new array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM