之前已经折腾过基本的ReactJS,也用过(别人弄好的)过Preact中的promise,
现在想要去搞清楚,ReactJS的项目中,获取网络数据,用哪个http库比较好。
react js http client
react js http库
5 best libraries for making AJAX calls in React – Hashnode
Fetch
Superagent
Axios
Request
哪个好?
建议用:fetch
reactjs – is there any good Http library for React flux architecture – Stack Overflow
react js http lib
react js http fetch vs Superagent
3 Libraries and 3 Ways to Handle AJAX in React Apps | appendTo
感觉还是fetch不错,简洁好用。
AJAX Requests in React: How and Where to Fetch Data
通过这个对比, 建议最开始直接用fetch
Chrome和Safari直接就内置支持,无需第三方的库了。
而对于想要支持更多浏览器的话,建议用:
这个fetch的封装(polyfill)
github/fetch: A window.fetch JavaScript polyfill.
去使用:
github/fetch: A window.fetch JavaScript polyfill.
➜ rse_web git:(master) npm install whatwg-fetch –save npm WARN [email protected] requires a peer of webpack@1 || 2 || ^2.1.0-beta || ^2.2.0-rc but none was installed. npm WARN [email protected] requires a peer of react@^15.6.1 but none was installed. added 1 package in 9.565s |
【总结】
最后用:
import ‘whatwg-fetch’; fetch( ‘http://xxxxx/getProgressData’, { method : ‘POST’, headers : { ‘Content-Type’: ‘application/x-www-form-urlencoded; charset=UTF-8’, ‘Accept’: ‘application/json’ }, body: ‘currTime=2017-08-25&orgCode=SK316005’ } ) .then((resp) => { console.log(resp); let respJson = resp.json(); //typeof(respJson)= object console.log(‘respJson=’, respJson, ‘typeof(respJson)=’, typeof(respJson)); return respJson; }) .then((respJsonDict) => { console.log(‘parsed respJsonDict=’, respJsonDict); }); |
效果:
即返回的是object对象,是Response类型,其中json()之后得到的是Promise对象,也就是可以直接拿来使用的json对象了,然后就可以进行后序数据处理了。
注:
fetch的文档:
【后记】
后来发现:
axios/axios: Promise based HTTP client for the browser and node.js
比如fetch好用多了,十分推荐。
转载请注明:在路上 » 【已解决】ReactJS中好用的获取网络数据的http库