Fetch发送网络请求

1. 文档

  1. https://github.github.io/fetch/
  2. https://segmentfault.com/a/1190000003810652

2. 特点

  1. fetch: 原生函数,不再使用XmlHttpRequest对象提交ajax请求
  2. 老版本浏览器可能不支持

3. 相关API

  1. GET请求
fetch(url).then(function(response) {
    
    
    return response.json()
  }).then(function(data) {
    
    
    console.log(data)
  }).catch(function(e) {
    
    
    console.log(e)
  });
  1. POST请求
 fetch(url, {
    
    
    method: "POST",
    body: JSON.stringify(data),
  }).then(function(data) {
    
    
    console.log(data)
  }).catch(function(e) {
    
    
    console.log(e)
  })

在这里插入图片描述

import React, {
    
    Component} from 'react';
import PubSub from 'pubsub-js'
import axios from "axios";

class Search extends Component {
    
    
    search = async () => {
    
    
        // 获取用户的输入(连续解构赋值+重命名)
        const {
    
    keyWordElement: {
    
    value: keyword}} = this
        // 发送请求前通知List更新状态
        // this.props.updateAppState({isFirst: false, isLoading: true})
        PubSub.publish('zep', {
    
    isFirst: false, isLoading: true})

        // 发送网络请求---使用axios发送
        /*axios.get(`https://api.github.com/search/users?q=${keyword}`).then((response) => {
            // 请求成功后通知List更新状态
            // this.props.updateAppState({isLoading: false, users: response.data.items})
            console.log('Search组件发布消息')
            PubSub.publish('zep', {isLoading: false, users: response.data.items})

        },(error) => {
            // this.props.updateAppState({isLoading: false, err: error.message})
            PubSub.publish('zep', {isLoading: false, err: error.message})

        })
*/

        // 发送网络请求---使用fetch发送(未优化)
        /*fetch(`https://api.github.com/search/users?q=${keyword}`).then(
            (response) => {
                console.log('联系服务器成功了')
                return response.json() // 返回一个promise对象,则失败状态
            },
            (error) => {
                console.log('联系服务器失败了', error)
                return new Promise(() => {}) // 返回一个初始化的promise,来中断链式调用
            }
        ).then(
            (response) => {
                console.log('获取数据成功', response)
            },
            (error) => {
                console.log('获取数据失败', error)
            }
        )*/

        // 发送网络请求---使用fetch发送(优化)
        fetch(`https://api.github.com/search/users?q=${
      
      keyword}`).then(
            (response) => {
    
    
                console.log('联系服务器成功了')
                return response.json() // 如果返回一个promise对象,则then的结果为失败状态
            }
        ).then(
            (response) => {
    
    
                console.log('获取数据成功', response)
            }
        ).catch(
            (error) => {
    
    
                console.log('请求出错', error)
            }
        )
       /* try {
            const response = await fetch(`https://api.github.com/search/users?q=${keyword}`)
            const data = await response.json()
            // console.log(data)
            PubSub.publish('zep', {isLoading: false, users: data.items})

        } catch (error) {
            console.log('请求出错', error)
            PubSub.publish('zep', {isLoading: false, err: error.message})
        }*/
    }
    render() {
    
    
        return (
            <section className="jumbotron" style={
    
    {
    
    textAlign: "center"}}>
                <h3 className="jumbotron-heading">搜索github用户</h3>
                <div>
                    <input ref={
    
    c => this.keyWordElement = c} type="text" placeholder="输入关键词点击搜索"/>&nbsp;
                    <button onClick={
    
    this.search}>搜索</button>
                </div>
            </section>
        );
    }
}

export default Search;

4.1. 总结

  1. 设计状态时要考虑全面,例如带有网络请求的组件,要考虑请求失败怎么办。

  2. ES6小知识点:解构赋值+重命名
    let obj = {a:{b:1}}
    const {a} = obj; //传统解构赋值
    const {a:{b}} = obj; //连续解构赋值
    const {a:{b:value}} = obj; //连续解构赋值+重命名

  3. 消息订阅与发布机制
    1.先订阅,再发布(理解:有一种隔空对话的感觉)
    2.适用于任意组件间通信
    3.要在组件的componentWillUnmount中取消订阅

  4. fetch发送请求(关注分离的设计思想)

try {
    
    
						const response= await fetch(`/api1/search/users2?q=${
      
      keyWord}`)
						const data = await response.json()
						console.log(data);
					} catch (error) {
    
    
						console.log('请求出错',error);
					}

猜你喜欢

转载自blog.csdn.net/weixin_44827418/article/details/120586142
今日推荐