網絡請求是開發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()); })