第四章:react ajax

第四章:react ajax

4.1. 理解

4.1.1. 前置说明

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

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

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

4.1.2. 常用的 ajax 请求库

  1. jQuery: 比较重, 如果需要另外引入不建议使用

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

a. 封装 XmlHttpRequest 对象的 ajax

b. promise 风格

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

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

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

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

4.1.3. 效果

ajax

需求:

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

4.2. axios

4.2.1. 文档

https://github.com/axios/axios

4.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);
});

4.3. Fetch

4.3.1. 文档

  1. https://github.github.io/fetch/

  2. https://segmentfault.com/a/1190000003810652

4.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)
})

4.4. demo: github users

4.4.1. 效果

demo_users

4.4.2. 拆分组件

App

  • state: searchName/string

Search

  • props: setSearchName/func

List

  • props: searchName/string
  • state: firstView/bool, loading/bool, users/array, errMsg/string

4.4.3. 编写静态组件

4.4.4. 编写动态组件

componentWillReceiveProps(nextProps): 监视接收到新的 props, 发送 ajax
使用 axios 库发送 ajax 请求

ray, errMsg/string

4.4.3. 编写静态组件

4.4.4. 编写动态组件

componentWillReceiveProps(nextProps): 监视接收到新的 props, 发送 ajax
使用 axios 库发送 ajax 请求

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

码小余の博客

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值