umi搭建react+antd项目(四)axios请求数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26744901/article/details/84032479

1.下载axios

yarn add axios

2.在src下新建文件夹conf,再新增js文件:axiosConf.js

import axios from 'axios'

axios.defaults.baseURL = "http://localhost:8000/"//api前缀


const instance = axios.create({
  xsrfCookieName: 'xsrf-token'
});

instance.interceptors.request.use(function (config) {
  return config;
}, function (error) {
  return Promise.reject(error);
});

instance.interceptors.response.use(function (response) {
  return response.data
}, function (error) {
  return Promise.reject(error);
});
export default instance;

3.在index.js导入axios

import instance from '../conf/axiosConf';

4.在constructor初始化参数list

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

初始化请求在react的componentDidMount事件(在第一次渲染后调用)

componentDidMount() {
    instance.get("api/img").then(data => {
      this.setState({list: data.list});
      console.log(this.state.list);
    })
  }

在render中拼接div,最好做成组件,传参数,下一篇再说

render() {
    let userMessage;
    if (this.state.list.length == 0) {
      userMessage = <div></div>
    } else {
      userMessage=[]
      this.state.list.map((item, index) => {
        userMessage.push(<div key={index}>{item.src}</div>)
      })
    }
    return (
      <div>
        {userMessage}
        <Link to="/index2">
          index
        </Link>
      </div>
    )
  }

6.显示效果如下:访问http://localhost:8000/

7.完整index.js

import React, {Component} from 'react';
import Link from 'umi/link';
import instance from '../conf/axiosConf';

export default class index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      list: []
    }
  }

  componentDidMount() {
    instance.get("api/img").then(data => {
      this.setState({list: data.list});
      console.log(this.state.list);

    })
  }

  render() {
    let userMessage;
    if (this.state.list.length == 0) {
      userMessage = <div></div>
    } else {
      userMessage=[]
      this.state.list.map((item, index) => {
        userMessage.push(<div key={index}>{item.src}</div>)
      })
    }
    return (
      <div>
        {userMessage}
        <Link to="/index2">
          index
        </Link>
      </div>
    )
  }
}

 

没有更多推荐了,返回首页