我想从数组创建表数据,并在5个条目后,创建一个新行.反应



我有一个这样的映射函数:

function MyFunction({rows}) {
return(
rows
.map((info, index) => (
<td key = {someNum}>
<p>some info</p>
</td>
)));
}

,我想添加一些东西,在索引达到5后创建新行:

function MyFunction({rows}) {
return(
rows
.map((info, index) => (
{(index+1 %5 === 0 || index === 0) && <tr>}
<td key = {someNum}>
<p>some info</p>
</td>
{(index+1 %5 === 0) && </tr>}
)));
}

我不能让它工作,你有什么主意吗?

我已经尝试了很多不同的语法在那些花括号里,但似乎不知道如何做到这一点。

const chunk = (arr, size) => 
Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
arr.slice(i * size, i * size + size)
);
const results = chunk(rows, 5);
return(
results.map((array) => (
<>
<tr>
{array.map((info) => (
<td key = {someNum}>
<p>some info</p>
</td>
))}
</tr>
</>
))
)

我想你错过了一个返回语句

如果你使用像

这样的箭头函数
const myFunction = () => doSomething(); // you don't need return

但是如果你这样使用

const myFunction = () => {
return doSomething(); // you need return
}

在你的情况下

return(
rows
.map((info, index) => (
// here missing a return 
{(index+1 %5 === 0 || index === 0) && <tr>}
<td key = {someNum}> // 
<p>some info</p>
</td>
{(index+1 %5 === 0) && </tr>}
)));

相关内容