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
相关产品推荐
相关产品推荐

