React.js中IngredientsList组件内容不渲染问题求助
食谱应用IngredientsList组件不渲染问题的解决方法
这是一款基于Spoonacular API开发的食谱应用,所有展示数据均从该API获取。用户点击食谱卡片上的「View Recipe」按钮后,会展示对应食谱的详情,但目前仅能渲染出Ingredients的h2标题,其下方的IngredientsList组件内容未显示,且控制台无报错信息。曾怀疑无法访问extendedIngredients数组,但通过console.log(item)可正常打印对应对象;若清空Ingredient组件的div内容,仅保留h1元素则可正常渲染。
相关代码
父组件FoodDetails代码(根组件为App.jsx)
import { useEffect, useState } from "react"; import styles from "./FoodDetails.module.css"; import IngredientsList from "./IngredientsList"; export default function FoodDetails({ foodId }) { const [recipe, setRecipe] = useState({}); const [isLoading, setIsLoading] = useState(true); const URL = `https://api.spoonacular.com/recipes/${foodId}/information`; const API_KEY = ""; let UniqueKey = 0; useEffect(() => { async function fetchRecipe() { const res = await fetch(`${URL}?apiKey=${API_KEY}`); const data = await res.json(); console.log(data); setRecipe(data); setIsLoading(false); } if (foodId !== "") { fetchRecipe(); } }, [foodId]); if (foodId !== "") { return ( <div> <div className={styles.recipeContainer}> <h1 className={styles.recipeName}>{recipe.title}</h1> <img className={styles.recipeImage} src={recipe.image} alt="" /> <div className={styles.recipeDetails}> <span> ⏳<strong>{recipe.readyInMinutes} Minutes</strong> </span> <span> 👨👩👧👦 <strong>Serves {recipe.servings}</strong> </span> <span> <strong> {recipe.vegetarian ? "🥕 vegetarian" : "🥩 non-vegetarian"} </strong> </span> <span> <strong>{recipe.vegan ? "🐮 vegan" : ""}</strong> </span> <span> <strong> ${Math.floor(recipe.pricePerServing / 100)} Per Serving </strong> </span> </div> <div> <h2>Ingredients</h2> <IngredientsList recipe={recipe} isLoading={isLoading} /> </div> <div className={styles.recipeInstructions}> <h2>Instructions</h2> <ol> {isLoading ? ( <p>Loading....</p> ) : ( recipe.analyzedInstructions[0].steps.map((step) => ( <li key={(UniqueKey = UniqueKey + 1)}>{step.step}</li> )) )} </ol> </div> </div> </div> ); } }
问题代码片段
<div> <h2>Ingredients</h2> <IngredientsList recipe={recipe} isLoading={isLoading} /> </div>
IngredientsList子组件代码
import Ingredient from "./Ingredient"; export default function IngredientsList({ recipe, isLoading }) { return ( <div> {isLoading ? ( <p>Loading....</p> ) : ( recipe.extendedIngredients.map((item) => { <Ingredient item={item} />; }) )} </div> ); }
Ingredient子组件代码
export default function Ingredient({ item }) { return ( <div> <img src={`https://img.spoonacular.com/ingredients_100x100/` + item.image} alt="" /> <div> <h1>{item.name}</h1> <p> {item.amount} {item.unit} </p> </div> </div> ); }
问题原因与解决方法
核心问题
IngredientsList组件中map方法的回调函数没有返回<Ingredient>组件。你用大括号{}包裹回调逻辑,但未显式返回元素,导致map遍历后得到的是全为undefined的数组,自然不会渲染任何内容。
修复步骤
修改IngredientsList组件的map回调部分,两种方式任选其一:
- 去掉大括号,使用箭头函数的隐式返回:
recipe.extendedIngredients.map((item) => ( <Ingredient item={item} key={item.id} /> ))
- 保留大括号,添加显式
return:
recipe.extendedIngredients.map((item) => { return <Ingredient item={item} key={item.id} />; })
额外优化建议
- 给map遍历的元素添加唯一
key属性:使用API返回的item.id作为key,比自定义递增变量更可靠,避免React渲染时的性能问题与警告。 - 为Ingredient组件的img标签添加备用文本,比如
alt={item.name},提升页面可访问性。
内容的提问来源于stack exchange,提问作者Jonathan_Anon
相关产品推荐
相关产品推荐

