React电商项目中如何在map迭代时按3个元素一组展示商品?
解决React商品列表按每行3个展示的问题
你的核心问题是直接遍历整个商品数组生成<tr>,导致创建20行重复内容,且未正确处理索引分组。下面提供两种简单可行的解决方案:
方法一:先将数组分组为每行3个的二维数组
先写一个辅助函数把商品数组分割成每组3个的子数组,再遍历这个二维数组生成行和列:
function ProdDisplay(){ const[bitData, setbitData]=useState(null); // 数组分组辅助函数 const chunkArray = (arr, chunkSize) => { const result = []; for (let i = 0; i < arr.length; i += chunkSize) { result.push(arr.slice(i, i + chunkSize)); } return result; }; fetch('https://fakestoreapi.com/products') .then(result=>result.json()) .then(result=>setbitData(result)) // 处理分组后的数组 const chunkedProducts = bitData ? chunkArray(bitData, 3) : []; return( <div> <table> {chunkedProducts.map((rowProducts, rowIndex) => ( <tr key={rowIndex}> {rowProducts.map(product => ( <td key={product.id}> <IndProduct data={product}/> </td> ))} </tr> ))} </table> </div> ) }
方法二:直接利用索引判断生成行
不需要额外分组,通过索引取模判断,每3个元素生成一行,同时跳过重复的行渲染:
function ProdDisplay(){ const[bitData, setbitData]=useState(null); fetch('https://fakestoreapi.com/products') .then(result=>result.json()) .then(result=>setbitData(result)) return( <div> <table> {bitData && bitData.map((_, index) => { // 只在每一组的第一个元素位置生成行 if (index % 3 !== 0) return null; // 截取当前索引开始的3个商品 const rowProducts = bitData.slice(index, index + 3); return ( <tr key={index}> {rowProducts.map(product => ( <td key={product.id}> <IndProduct data={product}/> </td> ))} </tr> ); })} </table> </div> ) }
关键注意点
- 必须给每个
<tr>和<td>添加唯一key属性,优先使用商品的id而非索引,避免React渲染警告和性能问题。 - 原代码中未定义
index变量,这也是导致错误的原因之一,上述两种方法都正确处理了索引逻辑。
内容的提问来源于stack exchange,提问作者Desai Vibha
相关产品推荐
相关产品推荐

