https://blog.csdn.net/weixin_43675447/article/details/96463580
https://www.itying.com/

axios: https://www.npmjs.com/search?q=axios
fetch-jsonp:https://www.npmjs.com/package/fetch-jsonp
安装axios、fetch-jsonp:

npm install axios --save / npm install fetch-jsonp --save    

导入axios、fetch-jsonp:

import axios from 'axios';  /  import fetchJsonp from 'fetch-jsonp';

axios使用

import React from 'react'
import axios from 'axios'
class Axios extends React.Component {
    //渲染完成的生命周期
    componentDidMount(){
        //异常处理  抓异常
        try{
            //react加载本地json文件,需放在public文件里   端口号为http://localhost:3000/   页面加载出来为首页
            axios.get("list.json").then((res)=>{
                console.log(res);
            });
        }
        catch(err){
            throw err;
        }
    }
    render() {
        return (
            <div></div>
        );
    }
}
export default Axios;

axios的封装

import axios from 'axios'
class Http {
    static get(api, param) {
        return new Promise((res, rej) => {
            axios.get(api, param).then(result => {
                res(result);
            });
        })
    }
    static post(api, params) {
        return new Promise((res, rej) => {
            axios.post(api, params).then(result => {
                res(result);
            })
        });
    }
    static delete(api, params) {
        return new Promise((res, rej) => {
            axios.delete(api, params).then(result => {
                res(result);
            });
        })
    }
    static put(api, param) {
        return new Promise((res, rej) => {
            axios.put(api, param).then(
                (result) => {
                    res(result);
                }
            )
        })
    }
}
export default Http
//注:使用是引入Http,Http.get等

mock使用

//安装,需要建立本地设计
cnpm install mockjs
import Mock from 'mockjs'

//加载本地数据
import listinfo from './list.json'

//使用Mock里的mock方法  拦截ajax请求
Mock.mock("/list","get",{
    result:listinfo
});
export default Mock;

fetchjsonp的使用

import React from 'react'
import fetchjsonp from 'fetch-jsonp'
class Fetchjsonp extends React.Component {
    componentDidMount(){
        let api="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20";
        fetchjsonp(api).then((res)=>{
            //这里对数据进行操作   默认的
            return res.json();
        }).then((res)=>{
            console.log(res);
        }).catch((err)=>{
            console.log(err);
        });
    }
    render() {
        return (
            <div></div>
        );
    }
}
export default Fetchjsonp;
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐