React Native 的一個目標(biāo)是成為一個游樂場所,在這里我們可以嘗試不同的體系結(jié)構(gòu)和瘋狂的想法。自從瀏覽器使用起來不夠靈活,我們別無選擇,只能去實現(xiàn)整個堆棧。在這個我們并不打算改變什么的地方,我們試圖盡可能忠實于瀏覽器的 APIS。網(wǎng)絡(luò)協(xié)議棧是一個很好的例子。
XMLHttpRequest API 是在 iOS networking apis 之上實現(xiàn)的。與 web 顯著的區(qū)別是其安全模式:由于沒有 CORS 的概念,你可以從互聯(lián)網(wǎng)上的任一網(wǎng)站上進行閱讀。
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.php');
request.send();
請按照 MDN Documentation,一個對 API 進行了完整描述的文檔。
作為一個開發(fā)人員,你可能不會直接將 XMLHttpRequest 對象作為他的 API,因為這是一個非常繁瑣的工作。但事實上,他的實現(xiàn)和與瀏覽器 APIS 的兼容能夠使你使用第三方庫,例如,直接來自 npm 的 Parse 和 super-agent。
Fetch 是一種更好的網(wǎng)絡(luò) API,它的工作是通過標(biāo)準(zhǔn)委員會完成,并且已經(jīng)在火狐瀏覽器上可以使用。默認情況下在 React Native 上也是可用的。
fetch('https://mywebsite.com/endpoint.php')
.then((response) => response.text())
.then((responseText) => {
console.log(responseText);
})
.catch((error) => {
console.warn(error);
});