使用惯了jQuery封装好的ajax方法,这次在使用React项目开发时,着实令人着急,记录一下。
fetch
fetch是用来取代传统的XMLHttpRequest的。 它的优点很多,包括链式调用的语法、返回promise等。
下面就是最基本的fetch使用,默认是异步的。
fetch(url,{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: data, // data为传输对象
}).then(res => {
res.json().then(data => { // data为返回的对象
console.log(data);
});
}).catch(function(e) {
console.log("ERROR");
});
简洁版:
let option = {}; // 参数
options.method = 'post';
let data={};
options.body = JSON.stringify(data);
options.headers={
'Content-Type':'application/json'
};
fetch(url,option).then(res => res.json())
.then(data => console.log(data))
.catch(e => console.log("error", e))
如何同步调用
使用 async 和 await 关键词,不过听说对浏览器兼容性不好。
// 在方法前加上async关键词
async function fetchAsync () {
let response = await fetch(url);
let data = await response.json();
return data;
}
真实案例
getData=(id)=>{
let option = {}; // 参数
options.method = 'post';
let data={id:id};
options.body = JSON.stringify(data);
options.headers={
'Content-Type':'application/json'
};
fetch(baseUrl+"/xx/xxxx",option)
.then(res=> res.json())
.then(res=> {
if(res.status===200){
// 获取返回值,修改state
this.setState({
data:res.data.list
});
}
})
.catch(e => console.log("error", e));
}