1.下载axios
1
2 1yarn add axios
2
2.在src下新建文件夹conf,再新增js文件:axiosConf.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 1import axios from 'axios'
2
3axios.defaults.baseURL = "http://localhost:8000/"//api前缀
4
5
6const instance = axios.create({
7 xsrfCookieName: 'xsrf-token'
8});
9
10instance.interceptors.request.use(function (config) {
11 return config;
12}, function (error) {
13 return Promise.reject(error);
14});
15
16instance.interceptors.response.use(function (response) {
17 return response.data
18}, function (error) {
19 return Promise.reject(error);
20});
21export default instance;
22
23
3.在index.js导入axios
1
2
3 1import instance from '../conf/axiosConf';
2
3
4.在constructor初始化参数list
1
2
3
4
5
6
7 1constructor(props) {
2 super(props);
3 this.state = {
4 list: []
5 }
6 }
7
初始化请求在react的componentDidMount事件(在第一次渲染后调用)
1
2
3
4
5
6
7 1componentDidMount() {
2 instance.get("api/img").then(data => {
3 this.setState({list: data.list});
4 console.log(this.state.list);
5 })
6 }
7
在render中拼接div,最好做成组件,传参数,下一篇再说
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 1render() {
2 let userMessage;
3 if (this.state.list.length == 0) {
4 userMessage = <div></div>
5 } else {
6 userMessage=[]
7 this.state.list.map((item, index) => {
8 userMessage.push(<div key={index}>{item.src}</div>)
9 })
10 }
11 return (
12 <div>
13 {userMessage}
14 <Link to="/index2">
15 index
16 </Link>
17 </div>
18 )
19 }
20
6.显示效果如下:访问http://localhost:8000/
7.完整index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42 1import React, {Component} from 'react';
2import Link from 'umi/link';
3import instance from '../conf/axiosConf';
4
5export default class index extends Component {
6 constructor(props) {
7 super(props);
8 this.state = {
9 list: []
10 }
11 }
12
13 componentDidMount() {
14 instance.get("api/img").then(data => {
15 this.setState({list: data.list});
16 console.log(this.state.list);
17
18 })
19 }
20
21 render() {
22 let userMessage;
23 if (this.state.list.length == 0) {
24 userMessage = <div></div>
25 } else {
26 userMessage=[]
27 this.state.list.map((item, index) => {
28 userMessage.push(<div key={index}>{item.src}</div>)
29 })
30 }
31 return (
32 <div>
33 {userMessage}
34 <Link to="/index2">
35 index
36 </Link>
37 </div>
38 )
39 }
40}
41
42