从API中获取数据并动态地将其添加到表中



我正在动态添加行到我的表:

import React from 'react';
import axios from "axios";
class ShipmentsTable extends React.Component{
constructor(props) {
super(props);
this.state = {
shipments: [
{
requestType: "Request Type",
customerName: "",
email: "",
companyName: "",

},
]
};
this.listRequest = this.listRequest.bind();
}
getShipments = () =>{
axios.get("http://localhost:8000/app/shipments/list/")
.then((response) =>{
let result = response.data;
console.log(result.data);
}).catch((error) =>{
console.log(error);
});
}

listRequest = () => {
setTimeout(() => {
this.setState(() => ({
shipments: [
/* These objects need to be replaced with api fetched data */
{
requestType: "Request Type",
customerName: "kjldfsj",
email: "dlfkjsdlf",
companyName: "dfdsafdsa",

},
{
requestType: "Request Type",
customerName: "kjldfsj",
email: "dlfkjsdlf",
companyName: "dfdsafdsa",

}
]
}));
}, 1000);
};

componentDidMount() {
this.listRequest();
this.getShipments();
}

addRow = ({ requestType, customerName, email, companyName}) => {
return (
<tr>
<td>{requestType}</td>
<td>{customerName}</td>
<td>{email}</td>
<td>{companyName}</td>
</tr>
);
};

render(){
return(
<table className="submittedShipmentsTable">
<thead>
<tr id="myTableHeader">
<td>
<th>Request Type</th>
</td>
<td>
<th>Customer Name</th>
</td>
<td>
<th>Email</th>
</td>
<td>
<th>Company Name</th>
</td>
</tr>
</thead>
<tbody>
{/*Adding Rows Automatically*/}
{this.state.shipments.map((shipment, index) => this.addRow(shipment))}

</tbody>
</table>
);
}
}
export default ShipmentsTable;

我有对象显示在我的表如下,它在表中显示这些对象,但我想显示从api获取的数据,而不是:

listRequest = () => {
setTimeout(() => {
this.setState(() => ({
shipments: [
/* These objects need to be replaced with api fetched data */
{
requestType: "Request Type",
customerName: "kjldfsj",
email: "dlfkjsdlf",
companyName: "dfdsafdsa",

},
{
requestType: "Request Type",
customerName: "kjldfsj",
email: "dlfkjsdlf",
companyName: "dfdsafdsa",

}
]
}));
}, 1000);
};

我的问题:我要做的是将从api获取的数据动态地添加到liststrequest()方法中的出货对象中的表中。

仅设置为声明从API接收的数据

getShipments = () =>{
axios.get("http://localhost:8000/app/shipments/list/")
.then((response) => {
this.setState({ shipments: response.data });
}).catch((error) =>{
console.log(error);
});
}

最新更新