【问题标题】:Access array.length to render number from MongoDB database in React app在 React 应用程序中访问 array.length 以从 MongoDB 数据库中呈现数字
【发布时间】:2020-11-23 12:07:45
【问题描述】:

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

const SubmitDebtSchema = new Schema ({
  balance: [{
    balanceDate: Date,
    newBalance: Number
  }],
});

上述 Schema 的示例 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]}
       />

            )
        })

这会映射到我的数据库,并试图提取最后一个余额条目以在我的网页上呈现为道具。

从最后一个余额条目中,然后我想拉出 newBalance 数字以呈现在我的网页中。所以在这个例子中,余额等于 200。

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

我已经简化了我的调用,因为它还提取了其他条目详细信息,但为了简单起见,我删除了它们。通话的其余部分工作正常!所以其他的都不是问题,只是获取数组中的最后一个值。

谁能指出我在这里做错了什么?

【问题讨论】:

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

标签: javascript reactjs


【解决方案1】:

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

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

  return (
    <IndividualDebtCard key={debt._id}
      balance={debt.balance[debt.balance.length - 1].newBalance}
    />
  )
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多