React中对象数组使用map函数无法正确渲染seats字段值求助
问题原因
使用带花括号{}的箭头函数作为map回调时,没有显式编写return语句返回JSX元素,导致map遍历后返回的数组元素全为undefined,因此页面没有对应内容渲染,和你的源数据正确性无关。
解决方案
方案1:显式添加return语句
同时为渲染的列表元素添加key属性避免React告警,示例代码如下:
<div className="col-xl-5 col-lg-5 col-md-7 col-sm-7 col-xs-9 col-6" style={{paddingLeft:25}}> <h5><b>{bookingsData.movieName}</b></h5> <h5>{bookingsData.theaterName}</h5> <h5><small>{bookingsData.showTime}</small></h5> {bookingsData.bookedSeats.map((seatNos, index) => { console.log(seatNos.seats); // 显式return需要渲染的JSX元素 return <h5 key={index}><small>{seatNos.seats}</small></h5> })} </div>
key优先使用数据中的唯一字段,若无唯一字段可临时使用遍历下标index。
方案2:使用箭头函数隐式返回
省略花括号和return,用小括号包裹需要返回的JSX元素即可:
{bookingsData.bookedSeats.map((seatNos, index) => ( <h5 key={index}><small>{seatNos.seats}</small></h5> ))}
补充说明
你注释的写法{bookingsData.bookedSeats.seats}不生效,是因为bookedSeats是数组类型,不能直接访问数组实例上不存在的seats属性。如果你的业务场景中bookedSeats始终只有1条数据,也可以直接取下标访问,不需要遍历:
<h5><small>{bookingsData.bookedSeats[0]?.seats}</small></h5>
这里的?.是可选链运算符,避免bookedSeats为空时抛出报错。
内容的提问来源于stack exchange,提问作者Ryan Fonseka
相关产品推荐
相关产品推荐

