针对React中使用起来较为方便的几种数据请求方式进行了汇总,主要有以下三种:

注意:React的数据请求是在钩子函数:componentDidMount 中进行的

以下几种方式都是通过json-server模拟数据请求的接口(如果不清楚json-server的使用可以参考这里:json-server

1 axios
这种方法使用较为普遍,在vue中也是经常使用
使用前先下载一哈: npm i axios

 axios.get(' http://localhost:3000/datalist').then(res=>{
  console.log(res);
})

结果:
在这里插入图片描述

2 fetch方式
fetch是一种HTTP数据请求的方式,是XMLHttpRequest的一种替代方案。fetch不是ajax的进一步封装,而是原生js。Fetch函数就是原生js,没有使用XMLHttpRequest对象。【引自fetch

fetch('http://localhost:3000/datalist').then(res=>res.json()).then(res=>{
     console.log(res)
})

结果:
在这里插入图片描述

3 传统的ajax请求
这个大家应该都不陌生就不细说了,当然在react也是可以用它的

let xhr = new XMLHttpRequest();
xhr.addEventListener('load',handler);
xhr.open("GET",'http://localhost:3000/datalist');
xhr.send();
function handler(e){
    console.log(JSON.parse(e.currentTarget.response));
}

结果:
在这里插入图片描述

Logo

前往低代码交流专区

更多推荐