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

JSX中map()搭配reduce()函数出现NaN或Undefined问题求助

问题分析与解决方案

你的代码里reduce抛出NaN/undefined错误,核心是用错了reduce的应用场景,还有几个细节问题:

核心错误点

  • 你在map()返回的JSX元素数组上调用reduce(),此时reduce的初始值a是第一个JSX元素,和b.sellingPrice相加必然得到NaN(元素无法和数字做加法运算)。
  • reduce未设置初始值,当newItems为空时会直接报错。
  • 表单输入的sellingPrice如果是字符串类型,求和时也会出现NaN。
  • return语句后直接换行,触发JS自动分号插入机制,导致返回undefined。

修复后的代码示例

const [productName, setProductName] = useState("");
const [sellingPrice, setSellingPrice] = useState(0);
const [newItems, setNewItems] = useState([]);

// 单独抽离总价计算逻辑
const calculateTotal = () => {
  return newItems.reduce((total, item) => {
    // 强制转换为数字,避免字符串相加导致的NaN
    return total + Number(item.sellingPrice);
  }, 0); // 必须设置初始值0,确保空数组时返回0
};

const displayAddedItemList = () => {
  if (!visible) {
    const total = calculateTotal();
    return (
      <div>
        <div>Items</div>
        {/* 先渲染所有商品项 */}
        {newItems.map((item, index) => {
          // 必须添加key属性,避免React渲染警告,优先用商品唯一ID,临时用index替代
          return (
            <div key={index} className='itemsAdded'>
              <div className='eachItemAdded'>  
                <div>{item.productName}</div>
                <div>{item.sellingPrice}</div>
              </div>
              <div className='deleteEditFont'> 
                <FontAwesomeIcon icon={faTrashCan} />
              </div>
            </div>
          );
        })}
        {/* 单独渲染总价区域 */}
        <div className='totalItemsAdded'>
          <p>Total</p>
          <p>${total.toFixed(2)}</p> {/* toFixed保留两位小数,符合价格展示格式 */}
        </div>
      </div>
    );
  }
  return null; // visible为true时返回空或其他占位内容
};

额外注意事项

  • 添加商品到newItems时,要把sellingPrice转为数字类型,避免后续求和出错:
    const addItem = () => {
      setNewItems([...newItems, {
        productName,
        sellingPrice: Number(sellingPrice)
      }]);
      // 清空输入框
      setProductName("");
      setSellingPrice(0);
    };
    
  • map渲染列表时的key属性,尽量使用商品的唯一标识(比如后端返回的ID),不要依赖index(如果有删除、排序操作,index会导致渲染异常)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 09:27:49