React学习--发送请求的方式(axios与fetch)

前端项目发送请求的方式

(1)jQuery—$.get 容易回调地狱

(2)axios----axios.get Promise风格

以上俩种需要xhr,没有xhr就不能发,本质上是ajax请求

(3)fetch:系统自带的,直接发送,不需要xhr,也是Promise风格

axios发送请求

search = async () =>{
     
	const {
     value} = this.keyWordNode
    // http://api.github.com/search/users?q=xxxxx
    // 发送请求前更新状态
	this.props.updateAppState({
     isFirst:false,isLoading: true})
    PubSub.publish('msg',{
     isFirst:false,isLoading: true})
    	axios.get(`/api1/search/users2?q=${
       keyWord}`).then(
			response => {
     
				//请求成功后通知List更新状态
				PubSub.publish('atguigu',{
     isLoading:false,users:response.data.items})
			},
			error => {
     
				//请求失败后通知App更新状态
					PubSub.publish('atguigu',{
     isLoading:false,err:error.message})
			}
		) 
		}

fetch发送请求

    search = async () =>{
     
        const {
     value} = this.keyWordNode
        // http://api.github.com/search/users?q=xxxxx
        // 发送请求前更新状态
        // this.props.updateAppState({isFirst:false,isLoading: true})
        PubSub.publish('msg',{
     isFirst:false,isLoading: true})
        // fetch发送请求(未优化版本)
        // fetch(`/api1/search/users2?q=${value}`).then(
        //         response => {
     
        //             console.log('联系服务器成功了,但是还没有数据');
        //             // 返回一个Promise的实例,然后可以链式调用
        //             return response.json()
        //         },
        //         error => {
     
        //             console.log('联系服务器失败了,但是还没有数据',error);
        //             // 中断初始化量,返回一个初始化量的Promise
        //             return new Promise(()=>{})
        //          }
        // ).then(
        //     response => {
     
        //         console.log('拿到数据了',response);
        //         PubSub.publish('msg',{isLoading: false,users:response.items})
        //     },
        //     error => {
     
        //         console.log('失败了',error);
        //         PubSub.publish('msg',{isLoading: false,err:error})
        //     }
        // )
        // fetch发送请求(优化版本)
        // 兼容性不好
        try{
     
            const response = await fetch(`/api1/search/users?q=${
       value}`)
            const data = await response.json()
            PubSub.publish('msg',{
     isLoading: false,users:data.items})
        }catch (error) {
     
            PubSub.publish('msg',{
     isLoading: false,err:error})
        }

    }

说明:

  • 在未优化的版本中,fetch是一个Promise对象,第一个.then里面成功的回调表示,与浏览器链接成功,
  • 但此时的response里面并不包含后端返回的数据,而后端返回的数据存在于response.json()对象中,并且这个对象也是一个Promise对象,
  • 因此为了避免回调地狱问题,我们可以返回response.json(),也即返回一个Promise,再通过.then链式调用,获取后端返回的数据
  • 经过优化我们可以直接使用ES6中Promise的语法糖async与await,给最外层函数添加async,然后给fetch添加await,给fetch的第一次response添加await,表示异步调用,最后使用try…catch来进行异常捕获,以此来简单实现fetch发送请求

你可能感兴趣的:(前端学习,react.js,ajax,jquery)