网络请求是开发APP中不可或缺的一部分,好比最基本的获取用户订单数据/获取商品数据/提交表单到服务器等等都离不开网络请求,那么在RN中是如何进行网络请求的呢?
git
Fetch API提供了一个JS接口,用于进行网络操做,例如请求和响应。它还提供了一个全局fetch方法,该方法提供了一种简单,合理的方式来跨网络异步获取数据。es6
React Native 引入了Fetch,咱们能够在RN中使用全局的fetch()方法进行网络请求,而且不须要本身作额外的导入。github
对于XMLHttpRequest,Fetch能够与之相媲美,而且比之提供了更增强大以及灵活的特性,下面将会一一阐述,熟悉XMLHttpRequest的朋友能够一边学习下面的知识,一边进行两者之间的关联。
JS经过XMLHttpRequest(XHR)来执行异步请求,这个方式已经存在了很长一段时间了。虽说它很是有用,但在一些场景,它并非最好的解决方案。好比它在设计上不符合职责分离的原则,将输入/输出和用事件来追踪状态混杂在一个对象当中。并且,基于这种事件的模型,与es6中的Promise不太搭。
ajax
有一点须要注意的是,fetch与jQuery.ajax()主要存在如下两种不一样,请牢记:chrome
let url = `http://api.github.com/search/repositories?q=${this.searchKey}`; fetch(url) .then(response => response.text()) // 将response中的data转成string .then(responseText => { console.log(responseText); }) .catch(error => { console.log(error); })
这里咱们经过网络获取一个JSON文件,并将其打印到控制台中。最简单的用法就是只提供一个参数用来指明想fetch到的资源路径,而后返回一个包含响应结果的promise。
固然它只是一个HTTP响应,而不是真的JSON或者String。为了获取String的内容,咱们还须要使用text()方法来将response中的data转成String。
json
Promise fetch(input, init);api
fetch(url, { body: JSON.stringify(data), // 数据类型要和 ‘Content-Type’ header 保持一致 cache: 'no-cache', // default, no-cache, reload, force-cache, 或者 only-if-cached credentials: 'same-origin', // emit,same-origin, include headers: { 'user-agent': 'Mozilla/4.0 MDN Example', 'content-type': 'application/json' }, 'method': 'POST', // GET,POST, PUT,DELETE 'mode': 'cors', // no-cors, cors, same-origin 'redirect': 'follow', // manual, follow,error 'referrer': 'no-referrer', // client或no-referrer }) .then(response => response.json()) // 将数据解析成json
若是遇到网络故障,fetch将会调用reject,带上一个TypeError对象。
promise
须要注意的是: 一次请求没有调用reject并不表明请求就必定成功了,一般状况下咱们须要在resolved的状况,在判断Response.ok是否为true,以下:服务器
let url = `http://api.github.com/search/repositories?q=${this.searchKey}`; fetch(url) .then(response => { if (response.ok) { return response.text(); } throw new Error('Network response was not ok.'); }) .then(responseText => { console.log(responseText); }) .catch(error => { console.log(error.toString()); })