我在 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
uj5u.com熱心網友回復:
我用適當的 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 ;
}
}
在沙箱中,您可以看到它已正確拆分
沙盒
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/466518.html
上一篇:條件:根據后端回傳的資料更改圖示
