如何在React Js中划分每10行数据的列表,然后下一个数据集到右列?



我在useEffect函数中获取待办事项列表数组数据,现在我想显示每列10个数据的结果,并在一列显示10个数据后,下一个数据将设置为右列。

的例子:我有22个头衔。前1-10个标题将显示在第一列,11-20个标题将显示在第二列,21-30个标题将显示在其他列。

arr =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12日,13日,14日,15日,16日,17日,18日,19日,20日,21日,22日,23日)

我实际上想要这个输出。输入图片描述

这里的是我的原始数据,我试着这样表示。但是我不能显示每列10个数据:

import React, { useEffect, useState } from 'react';

const Home = () => {
const [collection, setCollection] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json())
.then(json => {
setCollection(json);
// console.log(json)
})
}, []);
let modified_collection = [];
if (collection.length > 0) {
modified_collection = collection.reduce((rows, key, index) => {
return ((index % 11 !== 10
? rows.push([key])
: rows[rows.length - 1].push(key))
&& rows);
}, []);
}
console.log(modified_collection);
return (
<div  >
{modified_collection.map((row, index) => (
<div key={index} className='row mt-3'>
{row.map((col, index) => (
<div key={index} className="col">
<div className='card ' >
<p> {col.title}</p>
</div>
</div>
))}
</div>
))}
</div>
)
}

export default Home

我用适当的css创建了一个简单的示例,以演示您的html

问题是你的数组被分割了。

试试这个

if (collection.length > 0) {
let numberOfColumns = collection.length / 10;
if (collection.length % 10 > 0) {
numberOfColumns++;
}
let index = 0;
for (let i = 0; i < collection.length; i++) {
if (index % numberOfColumns == 0) {
index = 0;
}
if (!modified_collection[index]) {
modified_collection[index] = [];
}
modified_collection[index].push(collection[i]);
index++;
}
}

在沙箱中,你可以看到它被正确地分割了

沙箱

相关内容

最新更新