學習本系列內容須要具有必定 HTML 開發基礎,沒有基礎的朋友能夠先轉至 HTML快速入門(一) 學習react
本人接觸 React Native 時間並非特別長,因此對其中的內容和性質瞭解可能會有所誤差,在學習中若是有錯會及時修改內容,也歡迎萬能的朋友們批評指出,謝謝ios
文章初版出自簡書,若是出現圖片或頁面顯示問題,煩請轉至 簡書 查看 也但願喜歡的朋友能夠點贊,謝謝web
componentDidMount
方法中建立 Ajex 請求,等到請求成功,再用 this.setState
方法從新渲染UIfetch 目前還不是 W3C 規範,是由 whatag 負責研發。與 Ajax 不一樣的是,它的 API 不是事件機制,而是採用目前流行的 Promise(MDN Promise) 方式處理json
格式:axios
fetch(url, init) .then((response) => { // 數據解析方式 }) .then((responseData) => { // 獲取到的數據處理 }) .catch((error) => { // 錯誤處理 }) .done();
init
是一個對象,他裏面包含了:
譯註:segmentfault
- body:不可傳對象,用JSON.stringify({...})也不能夠,在jQuery 中會自動將對象封裝成 formData 形式,fetch不會。
- mode屬性控制師傅跨域,其中 same-origin(同源請求,跨域會報error)、no-cors(默認,能夠請求其它域的資源,不能訪問response內的屬性)和 cros(容許跨域,能夠獲取第三方數據,必要條件是訪問的服務容許跨域訪問)。
- 使用 fetch 須要注意瀏覽器版本,但 React-Native 則不須要考慮。
response
對象能夠有以下幾種解析方式
fetch(url) .then((response) => response.json()) // json方式解析,若是是text就是 response.text() .then((responseData) => { // 獲取到的數據處理 }) .catch((error) => { // 錯誤處理 }) .done();
方式一:react-native
fetch(url, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" } body:"key1=value&key2=value…&keyN=value" }) .then((response) => { // 數據解析方式 }) .then((responseData) => { // 獲取到的數據處理 }) .catch((error) => { // 錯誤處理 }) .done();
方式二:跨域
let formData = new FormData(); formData.append("參數", "值"); formData.append("參數", "值"); 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: 窗體數據被編碼爲名稱/值對。這是標準的編碼格式。 multipart/form-data: 窗體數據被編碼爲一條消息,頁上的每一個控件對應消息中的一個部分。 text/plain: 窗體數據以純文本形式進行編碼,其中不含任何控件或格式字符。
- Fetch 跨域請求的時候默認是不帶 cookie 的,若是須要進行設置 credentials:'include'。
console.log(response.headers.get('Content-Type')); ... console.log(response.headers.get('Date'));
譯註:緩存
- 下面內容整理自 React-Native 中文網
React Native 中已經內置了 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();
注意:因爲安全機制與網頁環境有所不一樣:在應用中你能夠訪問任何網站,沒有跨域的限制
React Native 還支持 WebSocket
,這種協議能夠在單個TCP鏈接上提供全雙工的通訊信道
var ws = new WebSocket('ws://host.com/path'); ws.onopen = () => { // 打開一個鏈接 ws.send('something'); // 發送一個消息 }; ws.onmessage = (e) => { // 接收到了一個消息 console.log(e.data); }; ws.onerror = (e) => { // 發生了一個錯誤 console.log(e.message); }; ws.onclose = (e) => { // 鏈接被關閉了 console.log(e.code, e.reason); };