React 引入axios

1.進(jìn)入項(xiàng)目,安裝axios

npm install axios

2.對(duì)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,請(qǐng)求數(shù)據(jù)

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數(shù)據(jù)</button>
                {
                    this.state.list.map((item,key) => {
                        return (
                            <li key={key}>
                                {item.title}
                            </li>
                        )
                    })
                }
            </div>
        )
    }
}
export default Axios;

END----------

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,300評(píng)論 4 61
  • 如果需要在HTML頁面中插入js,js必須位于 標(biāo)簽之間。js可以放在HTML頁面的 和 中,或同時(shí)存在于兩個(gè)部...
    山的那邊海的那邊有太陽閱讀 359評(píng)論 0 0
  • 翻著以前在推塔里面寫的字,不是很勵(lì)志,甚至有些頹廢,找不到理由的頹廢。永遠(yuǎn)做不到理性的面對(duì)現(xiàn)實(shí),還總是活在給自己建...
    Hebetow閱讀 404評(píng)論 0 0
  • 2018年7月12日360落地實(shí)修第4天 本月9日我從泰安乘飛機(jī)回家,以為是兒子來接我,出了機(jī)場(chǎng)見到的是我家先生,...
    丁調(diào)調(diào)閱讀 232評(píng)論 0 0

友情鏈接更多精彩內(nèi)容