#javascript #reactjs #axios #jsx
#javascript #reactjs #axios #jsx
Вопрос:
Я извлекаю данные из API с помощью Axios. У меня есть метод listRequest(), который является запросом GET к API, метод 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, автоматически добавлялись в таблицу в виде строки
Ответ №1:
Для 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>
);
};
Комментарии:
1. Похоже, здесь работает: codesandbox.io/s/react-playground-forked-k16lv?file=/index.js