如何在表格中显示API响应数据

时间:2019-12-06 02:35:30

标签: reactjs api axios

我有以下代码,可以使用reactJs中的axios从API提取数据

/\d*\s\d*\s[NESW]{1}/

结果如下图所示

import React, { Component } from 'react';
import axios from 'axios';

export default class App extends Component {
  constructor(props) {
      super(props);
      this.state = {
          person: {}
      }
   }      

  componentDidMount() {
      axios.get('URL', {
        method: 'GET',
        headers: {
        'api-key': 'api-key goes here'
        }
    })
      .then((response) => {
          this.successShow(response);
      })
      .catch((error) => {
          this.successShow(error);
      });
  }
  successShow(response) {
      this.setState({
          person: response.data
      });
  }

  render() {
      return (
          <div>
            <h2>Welcome to React</h2>
            <p>{JSON.stringify(this.state.person.data)}</p>
            <div>{this.member}</div>
          </div>
         );
        }
   }

我想将数据显示为

{"Table":[{"id":1001,"first_name":"Adam","last_name":"Quda",.....}]}

我尝试了 First Name Last Name Adam Quda . . . . this.state.person.data.first_name,但有时会出错

  

未定义的函数名称{this.state.person.data.Table[].first_name}first_name ..

1 个答案:

答案 0 :(得分:1)

使用地图遍历数据,为每个对象创建一行。更改显示成功状态以将数组保存为状态,而不是对象。

successShow = response => {
  this.setState({
    // response format {"Table":[{"id":1001,"first_name":"Adam","last_name":"Quda",.....}]}
    person: response.data && response.data.Table
  });
};

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
</style>
<div id="root"></div>

<script type="text/babel">

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      person: [{ id: 1001, first_name: "Adam", last_name: "Quda" }]
    };
  }

  render() {
    return (
      <div>
        <table className="table">
          <tr>
            <th>Id</th>
            <th>First name</th>
            <th>Last name</th>
          </tr>
          {this.state.person.map(person => (
            <tr>
              <td>{person.id}</td>
              <td>{person.first_name}</td>
              <td>{person.last_name}</td>
            </tr>
          ))}
        </table>
      </div>
    );
  }
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
);
</script>