javascript - 自动将从 API 获取的数据添加到表中
问题描述
我正在使用 Axios 从 API 获取数据。我有一个 listRequest() 方法,它是对 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>
添加行将简单地返回该行:
addRow = ({ requestType, customerName, email, companyName }) => {
return (
<tr>
<td>{requestType}</td>
<td>{customerName}</td>
<td>{email}</td>
<td>{companyName}</td>
</tr>
);
};
推荐阅读
- c# - 将带有数字的字符串转换为字节数组 - C#
- python - 无法使用外键保存 Django 模型
- scala - 在程序中将状态单子结果从一个步骤传递到另一个步骤+提前停止
- tensorflow - 从 tfjs 加载 mobilenet 时出现等待错误
- ios - UITableViewCell 中的 UITextView 在 `textViewDidBeginEditing` 方法中第一次无法分配其委托
- javascript - 如何围绕与原点不同的实体点旋转
- python - 如何从熊猫数据框中提取每小时的第一行到新数据框
- java - 为什么数据没有插入 SQLite 数据库?(房间+rx)
- javascript - 在反应应用程序中上传图像的问题
- css - 允许在移动设备上放大 div 吗?