我有以下 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。
我已经简化了我的调用,因为它还提取了其他条目详细信息,但为了简单起见,我删除了它们。通话的其余部分工作正常!因此,其他任何事情都不是问题,只需获取数组中的最后一个值即可。
谁能指出我在这里做错了什么?