第4章:React ajax
4.1. 理解
4.1.1. 前置说明
- React本身只关注于界面, 并不包含发送ajax请求的代码
- 前端应用需要通过ajax请求与后台进行交互(json数据)
- react应用中需要集成第三方ajax库(或自己封装)
4.1.2. 常用的ajax请求库
- jQuery: 比较重, 如果需要另外引入不建议使用
- axios: 轻量级, 建议使用
- 封装XmlHttpRequest对象的ajax
- promise风格
- 可以用在浏览器端和node服务器端
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.data);
})
.catch(function (error) {
console.log(error);
});
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
2)POST请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
4.3. 案例—github用户搜索
4.3.1. 效果
请求地址: https://api.github.com/search/users?q=xxxxxx
4.4. 消息订阅-发布机制
- 工具库: PubSubJS
- 下载: npm install pubsub-js --save
- 使用:
- import PubSub from ‘pubsub-js’ //引入
- PubSub.subscribe(‘delete’, function(data){ }); //订阅
- PubSub.publish(‘delete’, data) //发布消息
4.5. 扩展:Fetch(了解)
4.5.1. 文档
- https://github.github.io/fetch/
- https://segmentfault.com/a/1190000003810652
4.5.2. 特点
- fetch: 原生函数,不再使用XmlHttpRequest对象提交ajax请求
- 老版本浏览器可能不支持
也没那么好用,真实项目中用到的也不多。
4.5.3. 相关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)
})
发送网络请求(优化前)
fetch(url).then(
response => {
console.log('联系服务器成功了);
return response.json()
},
error => {
console.log('联系服务器失败了);
return new Promise(()=>{})
}
).then(
response => {console.log('获取数据成功了,response);},
error => {console.log(‘获取数据失败了,error);}
)
优化
try {
const response = await fetch(url)
const data = awatit response.json().items
console.log(data)
} catch(error) {
console.log('请求出错',error)
}
使用 XHR 发送一个 json 请求一般是这样:
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = function() {
console.log(xhr.response);
};
xhr.onerror = function() {
console.log("Oops, error");
};
xhr.send();
4.6.Github搜索案例相关知识点
- 设计状态时要考虑全面,例如带有网络请求的组件,要考虑请求失败怎么办。
- ES6小知识点:解构赋值+重命名
let obj = {a:{b:1}} const {a} = obj; //传统解构赋值 const {a:{b}} = obj; //连续解构赋值 const {a:{b:value}} = obj; //连续解构赋值+重命名
- 消息订阅与发布机制
- 先订阅,再发布(理解:有一种隔空对话的感觉)
- 适用于任意组件间通信
- 要在组件的componentWillUnmount中取消订阅
- fetch发送请求(关注分离的设计思想)
try { const response = await fetch(url) const data = awatit response.json().items console.log(data) } catch(error) { console.log('请求出错',error) }