【发布时间】:2022-11-05 01:21:03
【问题描述】:
我的函数有问题,第二次执行时控制台返回错误“未捕获的引用错误:初始化前无法访问“总计”。值的总和没有问题,但我找不到函数给出此错误的原因。`
sumExpenses = () => {
const { expenses } = this.props;
const total = expenses.reduce((acc, e) => {
const parc = (Number(e.value) * Number(e.exchangeRates[e.currency].ask)).toFixed(2);
const final = Number(parc) + Number(acc);
console.log(final);
return total;
}, 0);
};
The error:
Uncaught ReferenceError: Cannot access 'total' before initialization
at WalletForm.js:31:1
at Array.reduce (<anonymous>)
at WalletForm.sumExpenses (WalletForm.js:27:1)
at WalletForm.handleClick (WalletForm.js:18:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1)
at executeDispatch (react-dom.development.js:9041:1)
at processDispatchQueueItemsInOrder (react-dom.development.js:9073:1)
`
我试图通过 redux 将交换价格表应用于费用应用程序。这些值在状态上看起来是正确的,但是当我添加第二笔费用时,导航器给了我一个错误。
【问题讨论】:
-
您在
reduce回调中调用return total,这没有任何意义,因为total是reduce的结果。我猜你想返回final -
但是当我把 final 放在 return 上时,VScode 给我分配了错误“total”,但使用了神经元。我找不到删除它的方法,有什么提示吗?感谢你的回答。
标签: javascript react-redux reduce