react ajax
前置说明
1)React本身只关注于界面, 并不包含发送ajax请求的代码
2)前端应用需要通过ajax请求与后台进行交互(json数据)
3)react应用中需要集成第三方ajax库(或自己封装)
常用的ajax请求库
1)jQuery: 比较重, 如果需要另外引入不建议使用
2)axios: 轻量级, 建议使用
a.封装XmlHttpRequest对象的ajax
b. promise风格
c.可以用在浏览器端和node服务器端
3)fetch: 原生函数, 但老版本浏览器不支持
a.不再使用XmlHttpRequest对象提交ajax请求
b.为了兼容低版本的浏览器, 可以引入兼容库fetch.js
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);
});//post
axios.post('/user', {
firstName:'Fred',
lastName:'Flintstone'})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
Fetch
文档:
相关API:
//get
fetch(url).then(function(response) {returnresponse.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)
})
例子:
Title/*需求:
1. 界面效果如下
2. 根据指定的关键字在github上搜索匹配的最受关注的库
3. 显示库名, 点击链接查看库
4. 测试接口: https://api.github.com/search/repositories?q=r&sort=stars*/class MostStarRepo extends React.Component {
constructor (props) {
super(props)this.state ={
repoName:'',
repoUrl:''}
}
componentDidMount () {
const url= `https://api.github.com/search/repositories?q=${this.props.searchWord}&sort=stars`
//const url = `https://api.github.com/search/repositories2?q=${this.props.searchWord}&sort=stars`
axios.get(url)
.then(response=>{
const result=response.data
console.log(result)
const repo= result.items[0]this.setState({
repoName: repo.name,
repoUrl: repo.html_url
})
})
.catch(error =>{//debugger
console.log(error)
alert('请求失败 '+error.message)
})/*fetch(url, {method: "GET"})
.then(response => response.json())
.then(data => {
console.log(data)
if(data.message) {
alert(`请求失败: ${data.message}`)
} else {
const repo = data.items[0]
this.setState({
repoName: repo.name,
repoUrl: repo.html_url
})
}
})*/}
render () {
const {repoName, repoUrl}= this.stateif(!repoName) {return
loading...
} else{return(
most star repo is{repoName}
)
}
}
}
ReactDOM.render(, document.getElementById('example'))