前言
學(xué)習(xí)本系列內(nèi)容需要具備一定 HTML 開發(fā)基礎(chǔ),沒有基礎(chǔ)的朋友可以先轉(zhuǎn)至 HTML快速入門(一) 學(xué)習(xí)
本人接觸 React Native 時間并不是特別長,所以對其中的內(nèi)容和性質(zhì)了解可能會有所偏差,在學(xué)習(xí)中如果有錯會及時修改內(nèi)容,也歡迎萬能的朋友們批評指出,謝謝
文章第一版出自簡書,如果出現(xiàn)圖片或頁面顯示問題,煩請轉(zhuǎn)至 簡書 查看 也希望喜歡的朋友可以點贊,謝謝
網(wǎng)路請求
- 在開發(fā)中,從網(wǎng)絡(luò)上加載數(shù)據(jù)一直是重點和難點,尤其是在做相應(yīng)的細節(jié)優(yōu)化方面,在React Native 中通常是用哪種方式加載網(wǎng)絡(luò)數(shù)據(jù)呢?
- React Native 中通常是通過 Ajax 從服務(wù)器獲取數(shù)據(jù),在
componentDidMount方法中創(chuàng)建 Ajex 請求,等到請求成功,再用this.setState方法重新渲染UI
- React Native 中通常是通過 Ajax 從服務(wù)器獲取數(shù)據(jù),在
什么是 fetch
fetch 目前還不是 W3C 規(guī)范,是由 whatag 負責(zé)研發(fā)。與 Ajax 不同的是,它的 API 不是事件機制,而是采用目前流行的 Promise(MDN Promise) 方式處理
格式:
fetch(url, init)
.then((response) => { // 數(shù)據(jù)解析方式
})
.then((responseData) => { // 獲取到的數(shù)據(jù)處理
})
.catch((error) => { // 錯誤處理
})
.done();
- 上面的示例中的
init是一個對象,他里面包含了:- method:請求方式(GET、POST、PUT等)。
- headers:需要用到 Headers 對象使用這個參數(shù)。
- body:需要發(fā)送的數(shù)據(jù)
- mode:跨域設(shè)置(cors, no-cors, same-origin)
- cache:緩存選項(default, no-store, reload, no-cache, force-cache, or only-if-cached)
譯注:
- body:不可傳對象,用JSON.stringify({...})也不可以,在jQuery 中會自動將對象封裝成 formData 形式,fetch不會。
- mode屬性控制師傅跨域,其中 same-origin(同源請求,跨域會報error)、no-cors(默認,可以請求其它域的資源,不能訪問response內(nèi)的屬性)和 cros(允許跨域,可以獲取第三方數(shù)據(jù),必要條件是訪問的服務(wù)允許跨域訪問)。
- 使用 fetch 需要注意瀏覽器版本,但 React-Native 則不需要考慮。
-
response對象可以有如下幾種解析方式- arrayBuffer()
- json()
- text()
- blob()
- formData()
下面是一個最基本的請求,只傳入一個參數(shù),默認為 GET 方式請求
fetch(url)
.then((response) => response.json()) // json方式解析,如果是text就是 response.text()
.then((responseData) => { // 獲取到的數(shù)據(jù)處理
})
.catch((error) => { // 錯誤處理
})
.done();
- 針對表單提交的請求,我們通常采用 POST 的方式。
方式一:
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
body:"key1=value&key2=value…&keyN=value"
})
.then((response) => { // 數(shù)據(jù)解析方式
})
.then((responseData) => { // 獲取到的數(shù)據(jù)處理
})
.catch((error) => { // 錯誤處理
})
.done();
- 在 JQuery 中,傳入對象框架會自動封裝成 formData 的形式,但是在 fetch 中沒有這個功能,所以我們需要自己初始化一個 FormData 直接傳給 body (補充:FormData也可以傳遞字節(jié)流實現(xiàn)上傳圖片功能)
方式二:
let formData = new FormData();
formData.append("參數(shù)", "值");
formData.append("參數(shù)", "值");
fetch(url, {
method:'POST,
headers:{},
body:formData,
}).then((response)=>{
if (response.ok) {
return response.json();
}
}).then((json)=>{
alert(JSON.stringify(json));
}).catch.((error)=>{
console.error(error);
})
譯注:
- application/x-www-form-urlencoded: 窗體數(shù)據(jù)被編碼為名稱/值對。這是標準的編碼格式。 multipart/form-data: 窗體數(shù)據(jù)被編碼為一條消息,頁上的每個控件對應(yīng)消息中的一個部分。 text/plain: 窗體數(shù)據(jù)以純文本形式進行編碼,其中不含任何控件或格式字符。
- Fetch 跨域請求的時候默認是不帶 cookie 的,如果需要進行設(shè)置 credentials:'include'。
獲取 HTTP 頭信息
console.log(response.headers.get('Content-Type'));
...
console.log(response.headers.get('Date'));
- 如果想了解更多,可以前往這個網(wǎng)址進行學(xué)習(xí):更多 fetch 學(xué)習(xí)點我
綜合實例
- 綜合實例直接放到了這里 React Native 之 實戰(zhàn)項目(一)
譯注:
- 下面內(nèi)容整理自 React-Native 中文網(wǎng)
其他可用網(wǎng)路庫
-
React Native 中已經(jīng)內(nèi)置了 XMLHttpRequest API,一些基于 XMLHttpRequest 封裝的第三方庫也可以使用(如:axios、frisbee)但不能使用 jQuery,因為 jQuery 中還使用了很多瀏覽器才有而RN中沒有的東西
var request = new XMLHttpRequest(); request.onreadystatechange = (e) => { if (request.readyState != 4) { return; } if (request.status === 200) { console.log('success', request.responseText); } else { console.warn('error'); } } request.open('GET', 'https://mywebsite.com/endpoint/'); request.send(); 注意:由于安全機制與網(wǎng)頁環(huán)境有所不同:在應(yīng)用中你可以訪問任何網(wǎng)站,沒有跨域的限制
WebSocket
-
React Native 還支持
WebSocket,這種協(xié)議可以在單個TCP連接上提供全雙工的通信信道var ws = new WebSocket('ws://host.com/path'); ws.onopen = () => { // 打開一個連接 ws.send('something'); // 發(fā)送一個消息 }; ws.onmessage = (e) => { // 接收到了一個消息 console.log(e.data); }; ws.onerror = (e) => { // 發(fā)生了一個錯誤 console.log(e.message); }; ws.onclose = (e) => { // 連接被關(guān)閉了 console.log(e.code, e.reason); };