React本身只关注于界面, 并不包含发送ajax请求的代码,前端应用需要通过ajax请求与后台进行交互(json数据),可以使用集成第三方ajax库(或自己封装)
常用的ajax请求库
jQuery: 比较重, 如果需要另外引入不建议使用
axios: 轻量级, 建议使用,封装XmlHttpRequest对象的ajax,promise风格,可以用在浏览器端和node服务器端
fetch: 原生函数, 但老版本浏览器不支持,不再使用XmlHttpRequest对象提交ajax请求,为了兼容低版本的浏览器, 可以引入兼容库fetch.js
常用的ajax请求库—axios
相关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);
});
相关API—post请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
常用的ajax请求库—fetch
由于 Fetch API 是基于 Promise 设计,有必要先学习一下 Promise,推荐阅读 MDN Promise 教程。旧浏览器不支持 Promise,需要使用 polyfill es6-promise
Fetch API 很简单,看文档很快就学会了。推荐 MDN Fetch 教程 和 万能的WHATWG Fetch 规范
相关API-get请求
fetch(url).then(function(response) {
return response.json()
}).then(function(data) {
console.log(data)
}).catch(function(e) {
console.log(e)
});
相关API-post请求
fetch(url, {
method: "POST",
body: JSON.stringify(data),
}).then(function(data) {
console.log(data)
}).catch(function(e) {
console.log(e)
})
分别使用axios和fetch实现一个搜索案例
效果大致如下
使用脚手架创建项目并且创建目录结构并且编写静态的组件
将这个功能抽出来一整个模块(search),将主组件在App.js中引入
search.js(主组件)
组件中需要接收子组件search-input.js传过来的一个searchName数据,search组件拿到这个数据进行请求后台,将返回的数据传递给子组件search-list
search-list有四个状态,初始(initView),查询中(loading),查询的数据(users),查询失败信息(errorMsg),在父组件中传递给子组件search-list并且根据查询结果进行更新这四个状态,