很多移動應用都需要從遠程地址中獲取數據或資源。你可能需要給某個 REST API 發起 POST 請求以提交用戶數據,又或者可能僅僅需要從某個服務器上獲取一些靜態內容。
使用 Fetch
React Native 提供了和 web 標准一致的Fetch API,用於滿足開發者訪問網絡的需求。
發起請求
要從任意地址獲取內容的話,只需簡單地將網址作為參數傳遞給 fetch 方法即可(fetch 這個詞本身也就是獲取的意思):
fetch('https://mywebsite.com/mydata.json');
Fetch 還有可選的第二個參數,可以用來定制 HTTP 請求一些參數。你可以指定 header 參數,
或是指定使用 POST 方法,又或是提交數據等等:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
提交數據的格式關鍵取決於 headers 中的Content-Type。Content-Type有很多種,對應 body 的格式也有區別。到底應該采用什么樣的Content-Type取決於服務器端,
所以請和服務器端的開發人員溝通確定清楚。常用的'Content-Type'除了上面的'application/json',還有傳統的網頁表單形式,示例如下:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'key1=value1&key2=value2',
});
注意:使用 Chrome 調試目前無法觀測到 React Native 中的網絡請求,你可以使用第三方的react-native-debugger來進行觀測。
我暫時還沒有到使用react-native-debugger的時候,到了再寫一篇關於這個使用的博客
處理服務器的響應數據
上面的例子演示了如何發起請求。很多情況下,你還需要處理服務器回復的數據。
網絡請求天然是一種異步操作(譯注:同樣的還有asyncstorage,請不要再問怎樣把異步變成同步!無論在語法層面怎么折騰,
、它們的異步本質是無法變更的。異步的意思是你應該趁這個時間去做點別的事情,比如顯示 loading,而不是讓界面卡住傻等)。
Fetch 方法會返回一個Promise,這種模式可以簡化異步風格的代碼。
function getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}
你也可以在 React Native 應用中使用 ES2017 標准中的async/await 語法:
// 注意這個方法前面有async關鍵字
async function getMoviesFromApi() {
try {
// 注意這里的await語句,其所在的函數必須有async關鍵字聲明
let response = await fetch(
'https://facebook.github.io/react-native/movies.json',
);
let responseJson = await response.json();
return responseJson.movies;
} catch (error) {
console.error(error);
}
}
別忘了 catch 住fetch可能拋出的異常,否則出錯時你可能看不到任何提示。
下面是使用fetch的一個小例子
import React from 'react';
import { FlatList, ActivityIndicator, Text, View } from 'react-native';
export default class FetchExample extends React.Component {
constructor(props){
super(props);
this.state = { isLoading: true }
}
componentDidMount() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.movies,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
render() {
if(this.state.isLoading){
return(
<View style={{flex: 1,padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return(
<View>
<FlatList
data={this.state.dataSource}
renderItem={({item}) => <Text>{item.title},{item.releaseYear}</Text>}
keyExtractor={(item, index) => item.id}
/>
</View>
)
}
}
我們在模擬器上面可以看到
模擬器上的數據,返回的就是我們請求並展示的
我們可以在瀏覽器看看到我們請求的數據類型
使用其他的網絡庫
React Native 中已經內置了XMLHttpRequest API(也就是俗稱的 ajax)。一些基於 XMLHttpRequest 封裝的第三方庫也可以使用,
例如frisbee或是axios等。但注意不能使用 jQuery,因為 jQuery 中還使用了很多瀏覽器中才有而 RN 中沒有的東西(所以也不是所有 web 中的 ajax 庫都可以直接使用)。
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();
需要注意的是,安全機制與網頁環境有所不同:在應用中你可以訪問任何網站,沒有跨域的限制。
WebSocket 支持
React Native 還支持WebSocket,這種協議可以在單個 TCP 連接上提供全雙工的通信信道。
var ws = new WebSocket('ws://host.com/path');
ws.onopen = () => {
// connection opened
ws.send('something'); // send a message
};
ws.onmessage = (e) => {
// a message was received
console.log(e.data);
};
ws.onerror = (e) => {
// an error occurred
console.log(e.message);
};
ws.onclose = (e) => {
// connection closed
console.log(e.code, e.reason);
};