25_ajax请求_使用fetch

本文介绍了一个使用React和Axios实现的GitHub仓库搜索应用示例,该应用能够根据关键字搜索GitHub上最受关注的仓库,并展示其名称及链接。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="example"></div>
<script type="text/javascript" src="../js/react.development.js"></script>
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<script type="text/javascript" src="../js/babel.min.js"></script>
<script type="text/javascript" src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js"></script>
<script type="text/babel">
    /*
    * 需求:
    *    1.界面效果如下
    *    2.根据指定的关键字在github上搜索匹配的最受关注的库
    *    3.显示库名,点击链接查看库
    *    4.测试接口:https://api.github.com/search/repositories?q=r&sort=stars
    */
    class MostStarRepo extends React.Component {
        state = {
            repoName: '',
            repoUrl: ''
        }

        //在这里发送异步ajax请求
        componentDidMount() {
            //1.使用axios发送
            const url = `https://api.github.com/search/repositories?q=r&sort=stars`;
            //因为是promise风格的,所以后面可以使用.then()
            axios.get(url).then(response => {
                //数据就在response里面
                const result = response.data
                //使用解构得到想要的数据
                const {name, html_url} = result.items[0];
                //更新状态
                this.setState({repoName: name, repoUrl: html_url})
            }).catch((error) => {
                alert(error.message)
            })
            //2.使用fetch发送异步ajax请求
            /*fetch(url).then(response => {
                return response.json()//response.json()实际上是一个promise对象
            }).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 <h2>LOADING......</h2>
            } else {
                return <h2>Most star repo is <a href={repoUrl}>{repoName}</a></h2>
            }
        }

    }

    ReactDOM.render(<MostStarRepo/>, document.getElementById('example'));
</script>
</body>
</html>

 

转载于:https://www.cnblogs.com/zhanzhuang/p/10726564.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值