在ReactJS中如何将多个长度相同的数组合并生成新数组
问题原因
你当前输出27条结果是因为使用了三层嵌套for循环,会生成三个数组所有元素的笛卡尔积组合,而非按对应索引位置匹配元素。由于你三个数组长度完全一致,仅需一层循环使用相同索引取值即可实现需求。
实现方案
React 中更推荐使用 map 方法直接渲染列表,示例代码如下:
const ingredientsList = () => { // 以 ingredients 数组为遍历基准,用相同索引取另外两个数组的对应元素 return recipe.ingredients.map((ingredient, index) => ( <li key={index}> {recipe.amount[index]} {recipe.size[index]} {ingredient} </li> )) }
如果需要先合并生成新数组再使用,可以用以下写法:
// 生成格式为 ["1 cup flour", ...] 的合并后数组 const mergedIngredients = recipe.ingredients.map((ingredient, index) => { return `${recipe.amount[index]} ${recipe.size[index]} ${ingredient}` })
如果坚持用 for 循环实现,只需保留一层循环即可:
const ingredientsList = () => { const listItems = [] for (let i = 0; i < recipe.ingredients.length; i++) { listItems.push( <li key={i}> {recipe.amount[i]} {recipe.size[i]} {recipe.ingredients[i]} </li> ) } return listItems }
注意事项
React 中渲染列表元素需要为每个子项添加唯一的 key 属性,上述示例中临时使用索引作为 key,若你的食材数据存在唯一 ID,建议替换为唯一 ID 作为 key,避免出现渲染异常。
内容的提问来源于stack exchange,提问作者Jacqueline
相关产品推荐
相关产品推荐

