React map函数中if条件判断筛选渲染元素失效如何解决
问题原因
你当前代码无法实现效果主要存在4个问题:
- 逻辑写反:
if(offers.status==='pending') return代表状态为pending时直接返回空,和你要的「pending才渲染」需求完全相反 - JS自动插入分号陷阱:return 后面直接换行的话,JS会默认在return后加
;,后面的article元素永远不会被返回 - JSX语法错误:article标签前后多了冗余的
<和/>字符,语法不合法 - 变量命名冲突:map的回调参数名和数组名都是
offers,容易引发作用域错误
修正后代码
<main className="grid-b"> {offers.map((offer, index) => { // 仅当状态为pending时返回article,否则返回null不渲染 if(offer.status === 'pending') { return ( <article key={index}> <div className="text-b"> <h3>Post ID: {index + 1}</h3> <p>Quantity (Kg): {offer.quantity}</p> <p>Unit Price (Rs): {offer.value}</p> <p>Expiry Date: {moment(offer.expiryDate).fromNow()}</p> <p>Offer Gives: {moment(offer.offerCreatedAt).fromNow()}</p> </div> </article> ) } return null })} </main>
关键修改说明
- 把map回调的参数从
offers改为offer,避免和外层数组重名 - 调整判断逻辑:符合
pending条件时才返回article元素,不符合条件直接返回null,React不会渲染null值 - 把需要返回的JSX用括号包裹,避免JS自动插入分号导致返回空的问题
- 修复了冗余的错误标签符号,保证JSX语法合法
- 补充了列表渲染必填的
key属性,若数组元素有唯一id,建议替换为key={offer.id}获得更好的渲染性能
如果你更喜欢简洁写法,也可以用逻辑与运算符实现同等效果:
<main className="grid-b"> {offers.map((offer, index) => offer.status === 'pending' && ( <article key={index}> <div className="text-b"> <h3>Post ID: {index + 1}</h3> <p>Quantity (Kg): {offer.quantity}</p> <p>Unit Price (Rs): {offer.value}</p> <p>Expiry Date: {moment(offer.expiryDate).fromNow()}</p> <p>Offer Gives: {moment(offer.offerCreatedAt).fromNow()}</p> </div> </article> ) )} </main>
内容的提问来源于stack exchange,提问作者Walpita
相关产品推荐
相关产品推荐

