简体   繁体   English

尝试对数据库数组中的值求和,在 React 前端返回“NaN”错误

[英]Attempting to sum values in database array returning 'NaN' error in React frontend

I'm attempting to take figures from an array of objects in my React frontend, MongoDB Database, and sum them together.我试图从我的 React 前端 MongoDB 数据库中的对象数组中获取数字,并将它们相加。

To do this, I have built a 'reduce' function, which I'm using on my state.为此,我构建了一个“reduce”函数,我正在我的状态中使用它。

const sumBalance = this.state.debts.reduce(function(previousValue, currentValue) {
          return (
            previousValue.balance + currentValue.balance
          )
        }, 0)

However, every time I try to access my app now I get a 'NaN' where the 'sumBalance' function is rendering.但是,每次我尝试访问我的应用程序时,我都会得到一个“NaN”,其中“sumBalance”函数正在呈现。

In case it's not clear, I am attempting to take the 'balance' value from each of my database objects, and sum them together.如果不清楚,我试图从我的每个数据库对象中获取“余额”值,并将它们相加。 I then want to render that in this component:然后我想在这个组件中渲染它:

<IndividualDebtSummary balance={sumBalance} monthly="£430"/>

Here's my MongoDB schema to be totally clear - I want to take the 'balance' from this, which I thought would be this.state.debts.balance, and so previousValue.balance in my function:这是我的 MongoDB 模式完全清楚 - 我想从中获取“平衡”,我认为这将是 this.state.debts.balance,所以我的函数中的 previousValue.balance:

const SubmitDebtSchema = new Schema ({
  creditCard: String,
  personalLoan: String,
  provider: String,
  balance: Number,
  limit: Number,
  monthly: Number,
  interest: Number,
  borrowed: Number
});

Here's my full component code:这是我的完整组件代码:

class IndividualDebts extends Component {
  constructor(props) {
    super(props)

    this.state = {
      debts: []
    }

  }

  componentDidMount() {
    axios.get("/api/fetchDebtCards")
    .then((response) => {
      this.setState({ debts: response.data })
    })
    .catch(e => {
      console.log(e)
    })
  }

  render() {

        const sumBalance = this.state.debts.reduce(function(previousValue, currentValue) {
          return (
            previousValue.balance + currentValue.balance
          )
        }, 0)

    return (
      <div>

            <IndividualDebtSummary balance={sumBalance} monthly="£430"/>

    </div>
        )
      }
    }

For reference - I have a separate 'fetchDebts' function and they render using 'map' - but I've not included them to keep the code a bit shorter.作为参考 - 我有一个单独的 'fetchDebts' 函数,它们使用 'map' 进行渲染 - 但我没有包含它们以保持代码更短一些。

Thanks, any help would be great.谢谢,任何帮助都会很棒。

That happens because on the first render your array is actually empty.发生这种情况是因为在第一次渲染时,您的数组实际上是空的。 Try to render the data only if the debts array has some values, like:仅当债务数组具有某些值时才尝试呈现数据,例如:

return (
      <div>

            {this.state.debts.length > 0 && <IndividualDebtSummary balance={sumBalance} monthly="£430"/>}

    </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM