And*_*sta 2 javascript arrays reactjs react-bootstrap
假设我有一个如下所示的数组:
const array = [0, 1, 2, 3, 4, 5, 6, 7]
Run Code Online (Sandbox Code Playgroud)
我想要做的是迭代 .map 函数中的每 2 个对象,但它需要在我的渲染中看起来像这样(注意我使用的是 React Bootstrap):
<Row>
<Col>array[0]</Col>
<Col>array[1]</Col>
</Row>
<Row>
<Col>array[2]</Col>
<Col>array[3]</Col>
</Row>
Run Code Online (Sandbox Code Playgroud)
等等...
因此,对于每 2 个对象,它需要拥有自己的行,然后在关闭 Row 并开始新 Row 之前渲染这 2 个对象(如果它有更多元素)。
实现这一目标的最佳方法是什么?
转换模型,然后注入视图。
您需要根据需要将数组转换为矩阵:
const array = [0, 1, 2, 3, 4, 5, 6, 7]
const rows = array.reduce(function (rows, key, index) {
return (index % 2 == 0 ? rows.push([key])
: rows[rows.length-1].push(key)) && rows;
}, []);
console.log(rows)Run Code Online (Sandbox Code Playgroud)
现在,您的模型已转换为这种格式
[ [0, 1] , [2, 3] , [4, 5] , [6, 7] ]
现在嵌套循环应该优雅地完成这项工作:
rows.map(row => (
<Row >
{ row.map(col => (<Col>{col}</Col>)) }
</Row>
))
Run Code Online (Sandbox Code Playgroud)
这个优雅的解决方案背后的工程是准备你的模型,然后你循环。
不确定,<Compo id="">当组件在循环中呈现时,React 是否仍然需要 id in (.eg: )。