react axios方式获取api数据接口

import React, { Component } from 'react';
import Record from './Record';
import axios from 'axios';

class Records extends Component {
  constructor() {
    super();
  
    this.state = {
      error: null,
      isLoaded: false,
      records: []
    };
  }

  componentDidMount() {
    axios.get('https://5aa780cb7f6fcb0014ee24aa.mockapi.io/api/v1/records').then(
      res => {
        this.setState({
          isLoaded: true,
          records: res.data
        });
      }
    ).catch(
      error => {
        this.setState({
          isLoaded: true,
          error
        })
      }
    )
  }

  render() {
    const { error, isLoaded, records } = this.state;
    if (error) {
      return <div>{ error.message }</div>;
    } else if (!isLoaded) {
      return <div>loading...</div>
    } else {
      return (
        <div>
          <h2>Records</h2>
          <table className='table table-bordered'>
            <thead>
              <tr>
                <th>Date</th>
                <th>Title</th>
                <th>Amount</th>
              </tr>
            </thead>
            <tbody>
              {records.map((record) => <Record {...record} key={record.id}/>)}
            </tbody>
          </table>
        </div>
      );
    }

    
  }
}

export default Records;

 

posted @ 2018-03-14 16:10  sunbey80  阅读(2724)  评论(0编辑  收藏  举报