第四章:react ajax
4.1. 理解
4.1.1. 前置说明
-
React 本身只关注于界面, 并不包含发送 ajax 请求的代码
-
前端应用需要通过 ajax 请求与后台进行交互(json 数据)
-
react 应用中需要集成第三方 ajax 库(或自己封装)
4.1.2. 常用的 ajax 请求库
-
jQuery: 比较重, 如果需要另外引入不建议使用
-
axios: 轻量级, 建议使用
a. 封装 XmlHttpRequest 对象的 ajax
b. promise 风格
c. 可以用在浏览器端和 node 服务器端
- fetch: 原生函数, 但老版本浏览器不支持
a. 不再使用 XmlHttpRequest 对象提交 ajax 请求
b. 为了兼容低版本的浏览器, 可以引入兼容库 fetch.js
4.1.3. 效果
需求:
- 界面效果如下
- 根据指定的关键字在 github 上搜索匹配的最受关注的库
- 显示库名, 点击链接查看库
- 测试接口: 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
- 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);
});
- 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. 文档
-
https://github.github.io/fetch/
-
https://segmentfault.com/a/1190000003810652
4.3.2. 相关 API
- GET 请求
fetch(url).then(function(response) {
return response.json()
}).then(function(data) {
console.log(data)
}).catch(function(e) {
console.log(e)
});
- 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. 效果
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 请求