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

 

 

原文地址:https://www.cnblogs.com/SCAU-gogocj/p/15330588.html