【React新手学习指南】04 React中如何发送ajax请求?

写在前面,大家好!我是【跨考菌】,一枚跨界的程序猿,专注于后台技术的输出,目标成为全栈攻城狮!这博客是对我跨界过程的总结和思考。如果你也对Java后端技术感兴趣,抑或是正在纠结于跨界,都可以关注我的动态,让我们一起学习,一起进步~
我的博客地址为:【跨考菌】的博客


上篇【React新手学习指南】03 React脚手架实操(适合新手) 介绍了React脚手架创建应用的案例。本文开始学习React ajax的相关内容。和【跨考菌】一起加油吧~

在这里插入图片描述

更多ajax的内容请参考博主的《Ajax编程基础》专栏。

如果你觉得对你有帮助的话,记得帮博主一键三连😊哦


1 概述

1.1 ajax说明

  1. React本身只关注于界面, 并不包含发送ajax请求的代码
  2. 前端应用需要通过ajax请求与后台进行交互(json数据)
  3. react应用中需要集成第三方ajax库(或自己封装)

1.2 常用的ajax请求库

  1. jQuery: 比较重, 如果需要另外引入不建议使用
  2. axios: 轻量级, 建议使用
    a. 封装XmlHttpRequest对象的ajax
    b. promise风格
    c. 可以用在浏览器端和node服务器端
  3. fetch: 原生函数, 但老版本浏览器不支持
    a. 不再使用XmlHttpRequest对象提交ajax请求
    b. 为了兼容低版本的浏览器, 可以引入兼容库fetch.js
    注:发送ajax请求的两种方式:1、封装xmlhttprequest;2、fetch方法

1.3 效果

需求:

  1. 界面效果如下
  2. 根据指定的关键字在github上搜索匹配的最受关注的库
  3. 显示库名, 点击链接查看库
  4. 测试接口: https://api.github.com/search/repositories?q=r&sort=stars

在这里插入图片描述

1.4 案例

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>11_ajax</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.17.1/axios.min.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 {
    constructor (props) {
      super(props)
      this.state = {
        repoName: '',
        repoUrl: ''
      }
    }
    
    componentDidMount () {
      const url = `https://api.github.com/search/repositories?q=${this.props.searchWord}&sort=stars`
      // const url = `https://api.github.com/search/repositories2?q=${this.props.searchWord}&sort=stars`
      // axios.get(url)
      //   .then(response => {
      //     const result = response.data
      //     console.log(result)
      //     const repo = result.items[0]
      //     this.setState({
      //       repoName: repo.name,
      //       repoUrl: repo.html_url
      //     })
      //   })
      //   .catch(error => {
      //     // debugger
      //     console.log(error)
      //     alert('请求失败 '+ error.message)
      //   })

      fetch(url, {method: "GET"})
        .then(response => response.json()) // 返回的数据是json类型的
        .then(data => {
          console.log(data)
          if(data.message) {
            alert(`请求失败: ${data.message}`)
          } else {
            const repo = data.items[0]
            this.setState({
              repoName: repo.name,
              repoUrl: repo.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 searchWord="react"/>, document.getElementById('example'))
</script>
</body>
</html>

2 axios

2.1 文档

https://github.com/axios/axios

2.2 相关API

  1. GET请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  1. POST请求
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

3 fetch

3.1 文档

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

3.2 相关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)
})

在这里插入图片描述
如果对你有帮助,记得帮博主一键三连😊哦

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值