React代码map函数报错:Parsing error: ',' expected 求助
问题解决:React map函数报错“Parsing error: ',' expected”
错误原因
你的代码在return语句中直接用{}包裹了recipes.map()的结果,这会被JavaScript解析为对象字面量而非JSX表达式,从而触发语法错误。React函数组件的return括号内需要返回单个JSX元素(或用Fragment/容器包裹多个元素),直接写{}不符合JSX语法规范。
修复后的代码
import React from "react"; const RecipeCard = () => { const recipes = [ { id: "recipe-id-1", name: "Tomato Soup", description: "Love red soup 😎", ingredient: [ { name: "tomato", measurement: 3, unit: "cup" }, { name: "water", measurement: 3, unit: "cup" }, ] }, { id: "recipe-id-2", name: "Potato Soup", description: "Love potato soup 😎", ingredient: [ { name: "potato", measurement: 3, unit: "cup" }, { name: "water", measurement: 3, unit: "cup" }, ] } ]; return ( // 用React Fragment包裹map结果,避免多余DOM节点 <> {recipes.map((recipe) => ( // 添加key属性,必须是列表中唯一的值 <div key={recipe.id} className="recipeCard"> <h2>{recipe.name}</h2> <p>{recipe.description}</p> <ul> {recipe.ingredient.map((ingredient, index) => ( // 配料列表用index当key(如果配料有唯一id,建议用id代替index) <li key={index}> {ingredient.name} - {ingredient.measurement} {ingredient.unit} </li> ))} </ul> </div> ))} </> ); }; export default RecipeCard;
关键修复点
- 移除
return中包裹map的外层{},改用<>(React Fragment)包裹所有生成的元素,确保返回单个JSX节点。 - 给
map生成的每个<div>添加key={recipe.id},符合React列表渲染的要求(避免警告,提升性能)。 - 配料列表的
<li>添加了key={index}(如果配料有唯一id,建议用id代替index)。
内容的提问来源于stack exchange,提问作者Ikura
相关产品推荐
相关产品推荐

