[英]React, render array in different divs, depending on the condition
例如,我們有對象數組;
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'}
];
我將制作數組映射后如何在React中獲取下面的結構? 這應該是通用的,因為我們不知道我們會得到的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>
嘗試首先按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>
))
您可以提前分組,然后使用標記渲染結果。
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; }
你可以試試這個
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.