zoukankan      html  css  js  c++  java
  • 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同步 来让异步的代码被我们分割开,达到一种”停止“的状态来关注异步的中间过程效果

     

     

  • 相关阅读:
    Git中清除远程仓库HTTPS认证信息的方法
    JDK8新增时间类型用在JPA中的问题
    5 个关于 API 中日期和时间设计规则
    时间标准基础知识UTC和ISO8601
    JDK8中的时间API
    2019第7周日
    顶级思维模式:推导事物的第一性原理
    JS的jsoneditor,用来操作Json格式的界面;json-editor用来根据json数据生成界面
    Java读写文件,中文乱码解决
    intellij idea 热部署、热加载设置方法
  • 原文地址:https://www.cnblogs.com/SCAU-gogocj/p/15330588.html
Copyright © 2011-2022 走看看