说明:
1)React本身只关注于界面,并不包含发送ajax请求的代码;
2)前端应用需要通过ajax请求与后台进行交互(json数据)
3)react应用中需要集成第三方ajax库(或自己封装)
一、axios
- 封装XmlHttpRequest对象的ajax
- promise风格
- 可以在浏览器端和node服务器端
1. 下载axios
cnpm i axios --save
2. 引入axios
import axios from 'axios'
3. 使用axios
// 使用axios发送异步ajax请求
const url = "https://api.github.com/search/repositories?q=r&sort=stars";
axios.get(url)
.then(response => {
const result = response.data
// 得到数据
const {name, html_url} = result.items[0]
// 更新状态
this.setState({repoName: name, repoUrl: html_url})
}).catch((error) => {
alert(error.message)
});
二、fetch
- 原生函数,但老版本浏览器不支持
- 不再使用XmlHttpRequest对象提交ajax请求
- 为了兼容低版本的浏览器,可以引入兼容库fetch.js
使用fetch
// 使用fetch发送异步ajax请求
const url = "https://api.github.com/search/repositories?q=r&sort=stars";
fetch(url).then(response => {
return response.json()
}).then(data => {
// 得到数据
const {name, html_url} = data.items[0]
// 更新状态
this.setState({repoName: name, repoUrl: html_url})
});
三、完整代码
import React, {Component} from 'react';
import axios from 'axios'
class SearchRepo extends Component {
state = {
repoName: "",
repoUrl: ""
}
componentDidMount() {
// 使用axios发送异步ajax请求
const url = "https://api.github.com/search/repositories?q=r&sort=stars";
axios.get(url)
.then(response => {
const result = response.data
// 得到数据
const {name, html_url} = result.items[0]
// 更新状态
this.setState({repoName: name, repoUrl: html_url})
}).catch((error) => {
alert(error.message)
});
// 使用fetch发送异步ajax请求
// fetch(url).then(response => {
// return response.json()
// }).then(data => {
// // 得到数据
// const {name, html_url} = data.items[0]
// // 更新状态
// this.setState({repoName: name, repoUrl: html_url})
// });
}
render() {
const {repoName, repoUrl} = this.state
if (!repoName) {
return <h3>LOADING...</h3>
} else {
return <h3>most star repo is <a href={repoUrl}>{repoName}</a></h3>
}
return (
<div>
</div>
);
}
}
export default SearchRepo;