美文网首页
React 引入axios

React 引入axios

作者: 马小帅mm | 来源:发表于2018-12-31 14:20 被阅读0次

    1.进入项目,安装axios

    npm install axios
    

    2.对axios二次封装

    /model/axios.js

    import Axios from 'axios';
    import qs from 'qs';
    const axios = Axios.create();
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
    axios.interceptors.request.use((config) => {
    
        if (config.method === 'post') {
            config.data = qs.stringify(config.data);
        }
    
        return config;
    });
    // Add a response interceptor
    axios.interceptors.response.use(
        (response) => {
            // Do something with response data
            let data = response.data;
            response.data = data.data;
    
            return response;
        },
        (error) => {
            // Do something with response error
            return Promise.reject(error);
        }
    );
    export default axios;
    

    3.页面引入axios.js,请求数据

    import React, { Component } from 'react';
    import axios from '../model/axios';
    
    class Axios extends Component {
        constructor(props){
            super(props);
            this.state = {
                list: []
            }
        }
        getData = () => {
            axios.get('https://www.easy-mock.com/mock/5b4eb12d56c59c6f56266215/api/order_list')
            .then((response) => {
                this.setState({
                    list: response.data
                })
            })
            .catch(function (error) {
                console.log(error);
            });
        }
        render(){
            return (
                <div>
                    <button onClick={this.getData}>获取axios数据</button>
                    {
                        this.state.list.map((item,key) => {
                            return (
                                <li key={key}>
                                    {item.title}
                                </li>
                            )
                        })
                    }
                </div>
            )
        }
    }
    export default Axios;
    

    END----------

    相关文章

      网友评论

          本文标题:React 引入axios

          本文链接:https://www.haomeiwen.com/subject/iswilqtx.html