fetch
一種以Promise為基礎(chǔ)的異步請求。
fetch(url).then(response => {
return response.json()
}).then( data => {
// 得到數(shù)據(jù)
const { name,html_url } = data.items[0];
// 更新狀態(tài)
this.setState({ repoName:name,repoUrl:html_url });
})
Axios
另一種異步請求方式
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) => {
console.log(error.message);
})
-
axios
是封裝的一個基于XMLHttpRequest對象的ajax,他的風(fēng)格是Promise風(fēng)格邪狞,可以運(yùn)行在瀏覽器和node端。 -
fetch
是原生函數(shù)痢畜,但是老版本的瀏覽器不支持,為了兼容低版本摆舟,還是需要引入兼容庫fetch.js彤悔。
fetch.js的作用是判斷瀏覽器是否支持fetch,若不支持則轉(zhuǎn)到使用XMLHttpRequest
例子
import React from "react"
import Axios from "Axios"
export default class Qingqiu extends React.Component{
constructor(props){
super(props);
this.state={
goodsId:"",
goodsName:""
}
}
render() {
const { goodsId, goodsName } = this.state;
if(goodsId == ""){
return <h2>loading...</h2>
}else{
return <h2>The first food is [{ goodsId }]( { goodsName } )</h2>
}
}
componentDidMount() {
const url = `http://jspang.com/DemoApi/oftenGoods.php`;
let _this=this;
Axios.get(url).then( response => {
const data = response.data;
console.log(data);
_this.setState(data[0]);
} ).catch(( error ) => {
console.log(error);
});
}
}