【问题标题】:how to show API response in table format in react js?如何在 React js 中以表格格式显示 API 响应?
【发布时间】:2020-07-30 16:31:04
【问题描述】:

我正在尝试访问 API 响应以及我想以表格格式显示的那个 API 的所有数据,我已经编写了一些代码,但响应没有以表格格式显示,也没有显示任何错误。我必须使用 Axios 进行 API 请求,我想我为 API 响应处理编写了一些错误的代码

import React from "react";

// reactstrap components
import {
  Card,
  CardHeader,
  CardBody,
  CardTitle,
  Table,
  Row,
  Col
} from "reactstrap";
import axios from 'axios';



class Tables extends React.Component {

  constructor() {
    super();
    this.state = {
      data: []
    }
  }

  componentDidMount() {
    const record = axios.get('https://jsonplaceholder.typicode.com/users')
      .then((response) => {
        //console.log(response.data);
        this.setState({
          data: [response.data]
        });
      });
  }




  render() {

    return (
      <>
        <div className="content">
          <Row>
            <Col>
              <Card>
                <CardHeader>
                  <CardTitle tag="h4">Simple Table</CardTitle>
                </CardHeader>
                <CardBody>
                      <Table responsive>
                            <thead className="text-primary">
                              <tr>
                                <th>Name</th>
                                <th>User-Name</th>
                                <th>Email</th>
                              </tr>
                              {
                                this.state.data.map((item, index) => {
                                  return (
                                    <div key={index}>
                                      <tr>
                                        <td> {item.name} </td>
                                        <td> {item.username} </td>
                                        <td> {item.eamil} </td>
                                      </tr>
                                    </div>
                                  )
                                })
                              }

                            </thead>
                          </Table>
                </CardBody>
              </Card>
            </Col>
          </Row>
        </div>
      </>
    );
  }
}

export default Tables;

【问题讨论】:

    标签: html reactjs api


    【解决方案1】:

    在您的componentDidMount 中,删除setState 中的括号,否则数据将是一个数组数组,而不仅仅是一个数组:

    this.setState({
       data: response.data
    });
    

    【讨论】: