You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 02:45:03