React Js嵌套数组迭代问题:如何提取每个食谱对应的全部ingredients
React嵌套数组迭代提取配料实现方案

1. 基础渲染实现(按食谱分别展示对应配料)
假设你的食谱数组结构和截图对齐,可直接使用双重map遍历实现渲染:
// 示例数据结构参考 const recipes = [ { id: 1, title: "玛格丽特披萨", ingredients: ["高筋面粉150g", "番茄沙司30g", "马苏里拉芝士80g", "罗勒叶3片"] }, // 剩余19个食谱对象... ] // 组件渲染代码 function RecipeList() { return ( <div className="recipe-wrapper"> {/* 第一层遍历:遍历所有食谱 */} {recipes.map(recipe => ( <div key={recipe.id} className="recipe-card"> <h2>{recipe.title}</h2> <h3>配料:</h3> <ul className="ingredient-list"> {/* 第二层遍历:遍历当前食谱的嵌套配料数组 */} {recipe.ingredients.map((ingredient, index) => ( <li key={index}>{ingredient}</li> ))} </ul> </div> ))} </div> ) }
2. 注意事项
- 外层遍历的key优先使用食谱的唯一id字段,避免列表更新时出现渲染异常
- 若配料数组存储的是对象而非纯字符串,替换
{ingredient}为对应字段即可,例如{ingredient.name} {ingredient.weight} - 若嵌套层级更深,在对应位置新增一层
map遍历即可适配
3. 扩展需求:提取所有食谱的全部配料到单个数组
如果需要把20个食谱的所有配料合并为一个扁平化数组,可直接使用flatMap方法:
const allIngredients = recipes.flatMap(recipe => recipe.ingredients)
内容的提问来源于stack exchange,提问作者Sintaxis Dev
相关产品推荐
相关产品推荐

