【问题标题】:Uncaught ReferenceError: Cannot access 'func' before initialization未捕获的 ReferenceError:在初始化之前无法访问 \'func\'
【发布时间】: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,这没有任何意义,因为totalreduce 的结果。我猜你想返回final
  • 但是当我把 final 放在 return 上时,VScode 给我分配了错误“total”,但使用了神经元。我找不到删除它的方法,有什么提示吗?感谢你的回答。

标签: javascript react-redux reduce


【解决方案1】:

您正在记录 final 但返回 total

 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 final ;
    }, 0);
  };

【讨论】:

    猜你喜欢
    • 2020-12-12
    • 2020-05-06
    • 2021-03-10
    • 2020-06-02
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    相关资源
    最近更新 更多