首页 > 解决方案 > 自动将从 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 中获取的数据自动以行的形式添加到表中

标签: javascriptreactjsaxiosjsx

解决方案


为了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>
 );
};

推荐阅读