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

React:如何基于状态自身属性初始化totalItems?报错原因及解决

错误原因分析

你写的自执行函数里的this并不指向正在创建的状态对象。在对象字面量的初始化阶段,对象还未完全创建完成,此时内部函数中的this在严格模式下是undefined,所以访问this.Items就会抛出"Cannot read properties of undefined"的错误。

解决办法

方法1:提前定义变量计算总和

先把Items数组单独定义,再计算总和,最后传入useState:

const initialItems = [
  { id: 1, amount: 1 },
  { id: 2, amount: 1 },
  { id: 3, amount: 1 },
  { id: 4, amount: 1 },
];
const initialTotal = initialItems.reduce((sum, item) => sum + item.amount, 0);

const [state, setState] = useState({
  Items: initialItems,
  totalItems: initialTotal
});

方法2:使用useState的函数初始化形式

利用useState支持传入初始化函数的特性,在函数内部完成数组定义和总和计算,这种方式初始化逻辑只会执行一次:

const [state, setState] = useState(() => {
  const items = [
    { id: 1, amount: 1 },
    { id: 2, amount: 1 },
    { id: 3, amount: 1 },
    { id: 4, amount: 1 },
  ];
  return {
    Items: items,
    totalItems: items.reduce((sum, item) => sum + item.amount, 0)
  };
});

额外建议

如果后续Items会动态更新,totalItems其实不需要存在状态里,直接通过state.Items.reduce(...)实时计算即可,这样能避免状态不一致的问题:

// 只存Items状态
const [items, setItems] = useState([
  { id: 1, amount: 1 },
  { id: 2, amount: 1 },
  { id: 3, amount: 1 },
  { id: 4, amount: 1 },
]);

// 实时计算总和
const totalItems = items.reduce((sum, item) => sum + item.amount, 0);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 17:17:24