简体   繁体   English

React,渲染数组在不同的div中,具体取决于条件

[英]React, render array in different divs, depending on the condition

For example we have the array of objects; 例如,我们有对象数组;

let arr = [
    {id: 10, name: 'hello10'}, 
    {id: 10, name: 'hello10'},
    {id: 13, name: 'hello13'},
    {id: 16, name: 'hello16'},
    {id: 17, name: 'hello17'},
    {id: 17, name: 'hello17'},
    {id: 17, name: 'hello17'}
];

After I will make array map how can get the structure below in React? 我将制作数组映射后如何在React中获取下面的结构? And this should be generic, because we don't know about id's we will get. 这应该是通用的,因为我们不知道我们会得到的id。

<div>
    <p>hello10</p>
    <p>hello10</p>
</div>
<div>
    <p>hello13</p>
</div>
<div>
    <p>hello16</p>
</div>
<div>
    <p>hello17</p>
    <p>hello17</p>
    <p>hello17</p>
</div>

Try with grouping your data by id first: 尝试首先按ID分组您的数据:

Object.values(
  arr.reduce((acc, item) => ({
    ...acc,
    [item.id]: (acc[item.id] || []).concat(item),
  }), {})
).map(group => (
  <div>
    {group.map(item => (
      <p>{item.name}</p>
    ))}
  </div>
))

You could group in advance and then render the result with the tags. 您可以提前分组,然后使用标记渲染结果。

 var array = [ { id: 10, name: 'hello10' }, { id: 10, name: 'hello10' }, { id: 13, name: 'hello13' }, { id: 16, name: 'hello16' }, { id: 17, name: 'hello17' }, { id: 17, name: 'hello17' }, { id: 17, name: 'hello17' }], grouped = array.reduce((r, o, i, a) => { if (o.id === (a[i - 1] && a[i - 1].id)) { r[r.length - 1].push(o); } else { r.push([o]); } return r; }, []); console.log(grouped); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You can try this 你可以试试这个

let dict = {};
let idArr = [];

const len = arr.length;

//We are grouping our data by id
arr.map((ar) =< {
    if(!dict[ar.id]){
        dict[arr[i].id] = [];
        idArr.push(arr[i].id);
    }
    dict[arr[i].id].push(arr[i]);
});

// Now we will generate the output
idArr.map((id) => {
    return <div>{dict[id].map((elem) => <p>{elem}</p>)}</div>
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM