我正在使用Axios从API获取数据。我有一个liststrequest()方法,它是对API的GET请求,addRow()方法用于自动向表添加行。
我希望能够自动添加行与获取的数据。
下面是我的代码:import React from 'react';
import axios from "axios";
class ShipmentsTable extends React.Component{
constructor(props){
super(props);
this.state = {
shipment: {
requestType: "Request Type",
customerName: "",
email: "",
companyName: "",
}
};
this.listRequest = this.listRequest.bind();
}
listRequest = () =>{
axios.get("http://localhost:8000/app/list/")
.then((response) =>{
let result = response.data;
console.log(result);
this.setState({shipment: result.data});
}).catch((error) =>{
console.log(error);
});
}
componentDidMount(){
this.listRequest();
}
addRow = () =>{
//destructuring
const {requestType, customerName, email, companyName} = this.state.shipment;
return this.state.shipment.map((shipment, index) =>{
<tr>
<td>{requestType}</td>
<td>{customerName}</td>
<td>{email}</td>
<td>{companyName}</td>
</tr>
});
}
render(){
return(
<table className="submittedShipmentsTable">
<thead>
<tr>
<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.addRow}
</tbody>
</table>
);
}
}
export default ShipmentsTable;
问题:
我希望从API获取的数据以行形式自动添加到表中
对于map
的工作,您需要一个数组,即:
this.state = {
shipments: [
{
requestType: "Request Type",
customerName: "",
email: "",
companyName: ""
}
]
};
然后你可以在渲染中这样做:
<tbody>
{this.state.shipments.map((shipment, index) => this.addRow(shipment))}
</tbody>
add row将简单地返回行:
addRow = ({ requestType, customerName, email, companyName }) => {
return (
<tr>
<td>{requestType}</td>
<td>{customerName}</td>
<td>{email}</td>
<td>{companyName}</td>
</tr>
);
};