• React中网络请求(axios和fetch)


    React中网络请求接口API

     

    axios请求:

    getStudentData = () => {
            axios.get('http://localhost:3000/api1/students').then(
                response => {console.log('成功了', response.data);},
                error => {console.log('getStudentData方法失败了', error)}
            )
        }

     

    fetch请求:

    • jquery和axios都是对xhr(xmlhttprequest)的封装

    • fetch和xhr是同一个级别的

     

    未优化代码

     fetch(`/api1/search/users?q=${keyWord}`).then(
                response => {
                    console.log('联系服务器成功了');
                    return response.json()
                },
            ).then(
                response => {console.log('获取数据成功了', response)},
            ).catch(
                error => console.log(error)
            )
    • fetch返回的是一个promise,通过response.json 可以获取到这个promise对象

    • 然后通过return response.json() 返回这个promise对象,之后在外面再通过 .then就跨域获取到这个promise并进行异步执行了

    • 可以看到进行了两次的then解析,也就是一个柯里化的过程了

     

    半优化

    基于:有promise就有async 和 await的存在

    const response = await fetch(`/api1/search/users?q=${keyWord}`)
    const data = await response.json()
    console.log(data)
    • 因为fetch返回的是一个promise,用response来接受这个promise

    • 再通过一个await来对这个promise进行处理即可了

     

    优化

    使用try catch来包裹await代码进行错误的接受

    try {
            const response = await fetch(`/api1/search/users?q=${keyWord}`)
            const data = await response.json()
            PubSub.publish('state',{ isLoading: false, users: data.items})
    ​
        } catch(error) {
            PubSub.publish('state',{ isLoading: false, err: error.message})
        }
    • 通过await一步一步的进行,其实是一种设计模式(关注分离设计模式)也就是通过await同步 来让异步的代码被我们分割开,达到一种”停止“的状态来关注异步的中间过程效果

     

     

  • 相关阅读:
    ibatis的log4配置
    ie6中DIV最小高度
    Redhat GRUB配置错误修复
    MySQL性能优化的21条经验
    Top 200的全球开发者BLOG
    IBM服务器配置内外网络配置
    php ftp_rawlist不显示目录问题
    PHP实现异步调用方法研究[转]
    20100823工作记录
    Web 2.0应用客户端性能问题十大根源
  • 原文地址:https://www.cnblogs.com/SCAU-gogocj/p/15330588.html
Copyright © 2020-2023  润新知