微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

24_ajax请求_使用axios

前置说明:

  1.React本身只关注页面,并不包含发送ajax请求的代码

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

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

常用的ajax库:

  1.jQuery:比较重,为了发送ajax请求而引用整个文件(不建议使用)

  2.axios:轻量级,建议使用!

    a.封装了XmlHttPRequest对象的ajax

    b.promise风格

    c.可以用在浏览器端和node服务器端

  3.fetch:原生函数,但老版本浏览器不支持

    a.不再使用XmlHttPRequest对象提交ajax请求

    b.为了兼容低版本的浏览器,可以引入兼容库fetch.js

代码

  //其中的地址貌似访问不到了

<!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() {
            //使用axios发送
            const url = `https://api.github.com/search/repositories?q=r&sort=stars`;
            //因为是promise风格的,所以后面可以使用.then()
            axios.get(url).then(response => {
                //数据就在reponse里面
                const result = response.data
                //使用解构得到想要的数据
                const {name,html_url} = result.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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐