react 请求数据并渲染

57 阅读1分钟
import React from 'react';
import axios from 'axios'

class Axios extends React.Component {
  //构造函数
  constructor() {
    super();
    //react定义数据
    this.state = {
      res: [],
      isShow: false
    }
  }

  //请求接口的方法
  getData = () => {
    var api = 'http://192.168.3.166:8088/entityList/querAircraftCarrier';
    axios.get(api)
      .then(response => {
        // handle success
        console.log(response);
        this.setState({
          res: response.data.rows
        })
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      });
  }

  render() {
    return (
      <div>
        <h2>axios获取数据</h2>
        <button onClick={this.getData}>获取api接口</button>
        {this.state.res.map(item => (
          <div key={item.id}>
            <span>{item.name}</span><span>{item.state}</span>
          </div>
        ))}
      </div>
    )
  }
}

export default Axios;