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事件(在第一次渲染后调用)