Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/474.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在React应用程序中访问array.length以从MongoDB数据库呈现数字_Javascript_Reactjs - Fatal编程技术网

Javascript 在React应用程序中访问array.length以从MongoDB数据库呈现数字

Javascript 在React应用程序中访问array.length以从MongoDB数据库呈现数字,javascript,reactjs,Javascript,Reactjs,我有以下Mongo模式,在“balance”中有一个对象数组: const SubmitDebtSchema = new Schema ({ balance: [{ balanceDate: Date, newBalance: Number }], }); 所述模式的示例console.log如下: balance: Array [ { id: "20304929403048fd636", balanceDate: &

我有以下Mongo模式,在“balance”中有一个对象数组:

const SubmitDebtSchema = new Schema ({
  balance: [{
    balanceDate: Date,
    newBalance: Number
  }],
});
所述模式的示例console.log如下:

balance: Array [
    {
      id: "20304929403048fd636",
      balanceDate: "2020-11-23T10:57:58.845Z",
      newBalance: 300
    },
    {
      id:"20fhdjfjwjh39g9395",
      balanceDate: "2020-11-23T11:54.58.845Z",
      newBalance: 200
    } ]
然后,我有一个Axios调用,该调用设置如下所示的数组状态:

  componentDidMount() {

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

  }
最后,我尝试使用以下函数在我的网页上呈现结果

const fetchDebts = this.state.debts.map (debt => {

      return (

       <IndividualDebtCard key={debt._id}
        balance={debt.balance[debt.balance.length - 1][2]}
       />

            )
        })
const fetchdeborts=this.state.deborts.map(debt=>{
返回(
)
})
这将映射到我的数据库中,并试图将最后一个余额条目作为道具呈现在我的网页上

const fetchDebts = this.state.debts.map (debt => {

      return (

       <IndividualDebtCard key={debt._id}
        balance={debt.balance[debt.balance.length - 1][2]}
       />

            )
        })
从这最后一个余额条目中,我想拉出新的余额图形,以在我的网页中呈现。在这个例子中,平衡等于200

但是,array.length不起作用。我似乎无法访问阵列中的最后一个newBalance

我简化了我的调用,因为它还拉取了其他条目细节,但为了简单起见,我删除了它们。其余的通话都很好!因此,获取数组中的最后一个值并不是问题


有人能指出我在这里做错了什么吗?

我认为发生错误是因为您正在使用对象数组并试图从balance对象获取第二个索引。例如,余额[1][2]未定义,因为您无法按索引访问对象。只能通过键访问对象。您可以尝试使用平衡[1].newBalance解决问题

const fetchDebts = this.state.debts.map (debt => {

  return (
    <IndividualDebtCard key={debt._id}
      balance={debt.balance[debt.balance.length - 1].newBalance}
    />
  )
})
const fetchdeborts=this.state.deborts.map(debt=>{
返回(
)
})

如果需要,我可以添加更多详细信息。