橙子

react 中使用axios

这里总结 react 中 axios 请求数据、拦截器

1 首先安装axios

npm install axios –save

2 引入axios

1
import axios from 'axios';

3 通过 axios 获取数据

todoList.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class TodoList extends Component {
componentDidMount () {
axios.get('/list.json').then(res => {
this.props.getInitList(res);
})
}

render () {
const { inpVal, list } = this.props;
return (
<div>
todoList
</div>
)
}
}

4 拦截器

拦截器就是一个箱子,把 axios 返回回来的东西放进去,然后返回一个经过处理的东西

todoList.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
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../store/actions/todoList';
import axios from 'axios';

// 处理返回的东西
axios.interceptors.response.use(res => {
if(res.data.code === 0) {
return res.data.data;
}
return Promise.reject('请求出错');
})

class TodoList extends Component {
componentDidMount () {
axios.get('/list.json').then(res => {
this.props.getInitList(res);
})
}

render () {
const { inpVal, list } = this.props;
return (
<div>
todoList
</div>
)
}
}

当每次请求都会设置token时,可以统一设置token:

1
2
3
4
axios.interceptors.request.use(config => {
config.headers.token = 'slkjkdflksdflksdjflksdhfl';
return config;
})