我正在尝试从MongoDB
数据库中获取数据。我已经保存了数据,这就是它的样子。
[
{
"_id": "5d977c6771384613e9b305ea",
"vendor": "2",
"invoiceDate": "2019-10-04T00:00:00.000Z",
"expectedDate": "2019-10-19T00:00:00.000Z",
"billingAddress": "Hi",
"contactPerson": "Machan",
"items": [
{}, // what is this? I don't know how an empty element is created
{
"_id": 2,
"qty": 0,
"unitPrice": 10,
"linePrice": 10
},
{
"_id": 5,
"qty": 12,
"unitPrice": 10,
"linePrice": 10
}
],
"totalPrice": 10,
"__v": 0
}
]
我正在从axio
获取这些数据,并像这样将它们保存在state
的{{1}}中:
这是我要存储的ReactJS
数组的state
属性:
items
这就是我从this.state = {
items:[{}]
}
获取数据并将其存储在MongoDB
state
如您所见,我的数据库中有两个 componentDidMount() {
let getPathName = window.location.pathname;
let pathName = getPathName.slice(13);
this.setState({
invoiceIdFromUrl: pathName
});
//fill the fileds
axios
.get(
"http://localhost:4005/purchaseinvoices/" + this.props.match.params.id
)
.then(response => {
var invoiceDate = new Date(
response.data.invoiceDate
).toLocaleDateString("en-US", {
year: "numeric",
month: "2-digit",
day: "2-digit"
});
var arr = [];
arr = invoiceDate.toString().split("/");
var invoiceDateNew = arr[2] + "-" + arr[0] + "-" + arr[1];
var expectedDate = new Date(
response.data.expectedDate
).toLocaleDateString("en-US", {
year: "numeric",
month: "2-digit",
day: "2-digit"
});
var arr2 = [];
arr2 = expectedDate.toString().split("/");
var expectedDateNew = arr2[2] + "-" + arr2[0] + "-" + arr2[1];
this.setState({
invoiceID: response.data._id,
vendorName: response.data.vendor,
invoiceDate: invoiceDateNew,
expectedDate: expectedDateNew,
address: response.data.billingAddress,
contactPerson: response.data.contactPerson,
rows: [...this.state.rows, response.data.items]
});
});
}
,其中items
的 2和5
但是每次我发出警报(this.state.rows.length)时,我只会在应该得到_id
的地方得到2
(因为{{1 }}是一个空数组,长度为1,并且在我尝试打印3
数组时,仅会打印 _id = 2的第一项。
有人可以告诉我我哪里出问题了吗?