ReactJS如何渲染对象数组?订餐应用开发新手报错求助
你的代码存在3个核心问题,直接导致运行报错:
- 组件定义顺序错误:你在
Card组件内部先调用MealItems做数组映射,之后才定义MealItems组件。const声明的变量不存在变量提升,调用时MealItems还未被定义,属于未定义变量报错。
- 组件定义顺序错误:你在
MealItems组件没有返回JSX:箭头函数如果用花括号包裹逻辑,需要显式写return返回要渲染的结构,否则返回值是undefined,渲染空内容会报错。
- 标签语义不匹配:你返回的
MealItems是普通div结构,外层却用了<ul>无序列表包裹,不符合HTML语义规范,会触发控制台警告。
- 标签语义不匹配:你返回的
修复后的完整代码
import './css/foa-navigation.css'; // 模拟餐品数据 const DUMMY_MEALS = [ { id: 'm1', name: 'Triple B', description: 'Triple B burger for extreme meat lovers to feel the taste of 480 g (160 g x 3) charcoal grilled gourmet meat with melted cheese, lettuce and sauce in 4.5" ban.', price: 75, }, { id: 'm2', name: 'Pina Colada', description: 'Charcoal grilled gourmet beef patty with pineapple, bacon, white cheese & pina colada sauce.', price: 44, }, { id: 'm3', name: 'Mushroom Burger', description: 'Charcoal grilled gourmet beef patty with homemade pickles, mayo, Cheddar cheese, fresh mushrooms & rich homemade mushroom sauce', price: 44, }, { id: 'm4', name: 'Mexican Burger', description: 'Charcoal grilled gourmet beef patty with homemade pickles, mayo, jalapeno, Emmental cheese & Mexican sauce.', price: 44, }, { id: 'm5', name: 'Lads 70’s B', description: 'Charcoal grilled gourmet beef patty, homemade pickles, fresh mushrooms, grilled onions, egg, Cheddar & mozzarella cheese.', price: 44, }, { id: 'm6', name: 'Hot Dog', description: '-', price: 28, }, { id: 'm7', name: 'Double B', description: 'Double taste for meat lovers! 320 g (160 g x 2) of charcoal grilled patty with double cheese, lettuce and sauce in 4.5" ban.', price: 55, }, { id: 'm8', name: 'Classic Burger', description: 'Charcoal grilled gourmet beef patty with iceberg lettuce, tomatoes, homemade pickles, onions, Cheddar cheese & chef’s sauce.', price: 39, }, { id: 'm9', name: 'Big Lads', description: 'Charcoal grilled gourmet beef patty with iceberg lettuce, tomatoes, onions, mango, avocado, bacon, beetroot, mayo & white cheese.', price: 55, }, ]; // 单独抽离餐品项组件,避免作用域和定义顺序问题 const MealItems = (props) => { // 显式return渲染结构 return ( <li className="col-md-4"> <div className="item-add"> <div className="product_header"> <div className="product_name"> <span className="item-heading">{props.name}</span> </div> </div> <div className="product_price"> <span className="item-price"> {props.price}<span> $</span> </span> </div> <div className="product_description"> {props.description} </div> </div> </li> ) } const Card = () => { const mealsList = DUMMY_MEALS.map((meal) => ( <MealItems key={meal.id} id={meal.id} name={meal.name} description={meal.description} price={meal.price} /> )); return ( <div> <ul>{mealsList}</ul> </div> ); } export default Card;
核心原理解释
- 组件定义顺序规则:React组件本质是JS变量,
const/let声明的变量必须先定义后使用,不存在变量提升。建议子组件抽离到父组件外部定义,避免作用域和顺序问题。 - 箭头函数返回规则:箭头函数如果逻辑用花括号
{}包裹,必须显式写return返回要渲染的JSX;如果省略花括号,可以直接写JSX做隐式返回,比如const MealItems = (props) => (<div>...</div>)也能生效。 - 列表渲染语义规范:使用
<ul>渲染列表时,子元素必须是<li>标签,既符合HTML语义,也能避免控制台警告。
内容的提问来源于stack exchange,提问作者IcyHarka
相关产品推荐
相关产品推荐

