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

ReactJS中如何筛选仅显示inStock: true的有库存商品?

筛选仅库存可用(inStock: true)的商品

解决方法

在渲染商品列表的代码中,先对商品数组做过滤处理,只保留inStock为true的商品,再进行遍历渲染:

核心代码修改

// 先过滤库存可用的商品,再遍历渲染
products.filter(product => product.inStock).map(product => (
  // 保留你原有的商品项渲染逻辑,示例:
  <div key={product.id} className="product-card">
    <h2>{product.title}</h2>
    <p>价格: ${product.price}</p>
    {/* 其他商品信息 */}
  </div>
))

补充说明

  • filter()方法会生成新数组,只包含满足inStock为真的元素
  • 把过滤操作放在map()之前,就能保证只有库存可用的商品被展示
  • 如果需要兼容特殊场景(比如inStock可能是字符串"true"),可以写成严格判断:
    products.filter(product => product.inStock === true).map(...)
    

内容的提问来源于stack exchange,提问作者Sarah Barlis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:05:13