【React】两种方式发送异步ajax请求

说明:

1)React本身只关注于界面,并不包含发送ajax请求的代码;

2)前端应用需要通过ajax请求与后台进行交互(json数据)

3)react应用中需要集成第三方ajax库(或自己封装)

一、axios

  •  封装XmlHttpRequest对象的ajax
  •  promise风格
  •  可以在浏览器端node服务器端

1. 下载axios

cnpm i axios --save

2. 引入axios

import axios from 'axios'

 3. 使用axios

 // 使用axios发送异步ajax请求
        const url = "https://api.github.com/search/repositories?q=r&sort=stars";
        axios.get(url)
            .then(response => {
                const result = response.data
                // 得到数据
                const {name, html_url} = result.items[0]
                // 更新状态
                this.setState({repoName: name, repoUrl: html_url})
            }).catch((error) => {
            alert(error.message)
        });

二、fetch

  •  原生函数,但老版本浏览器不支持
  •  不再使用XmlHttpRequest对象提交ajax请求
  • 为了兼容低版本的浏览器,可以引入兼容库fetch.js

使用fetch

// 使用fetch发送异步ajax请求
        const url = "https://api.github.com/search/repositories?q=r&sort=stars";
        fetch(url).then(response => {
            return response.json()
        }).then(data => {
            // 得到数据
            const {name, html_url} = data.items[0]
            // 更新状态
            this.setState({repoName: name, repoUrl: html_url})
        });

三、完整代码

import React, {Component} from 'react';
import axios from 'axios'

class SearchRepo extends Component {
    state = {
        repoName: "",
        repoUrl: ""
    }

    componentDidMount() {
        // 使用axios发送异步ajax请求
        const url = "https://api.github.com/search/repositories?q=r&sort=stars";
        axios.get(url)
            .then(response => {
                const result = response.data
                // 得到数据
                const {name, html_url} = result.items[0]
                // 更新状态
                this.setState({repoName: name, repoUrl: html_url})
            }).catch((error) => {
            alert(error.message)
        });
        // 使用fetch发送异步ajax请求
        // fetch(url).then(response => {
        //     return response.json()
        // }).then(data => {
        //     // 得到数据
        //     const {name, html_url} = data.items[0]
        //     // 更新状态
        //     this.setState({repoName: name, repoUrl: html_url})
        // });

    }

    render() {
        const {repoName, repoUrl} = this.state
        if (!repoName) {
            return <h3>LOADING...</h3>
        } else {
            return <h3>most star repo is <a href={repoUrl}>{repoName}</a></h3>
        }
        return (
            <div>
            </div>
        );
    }
}

export default SearchRepo;

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zqq_2016

有用的话,来打赏博主吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值