网络通信
大部分移动端 APP 通过请求URL
于远程服务器上拉取数据资源。你可以通过对REST API
发起POST
请求以交互用户数据。亦或者仅仅需要获取(fetch
)其它服务器上的静态资源。
Using Fetch - 使用 Fetch
React-native
提供了一套供给开发者进行网络访问需求的 Fetch API
( 与 Web 标准一致 )。Fetch
与所谓的AJAX(XMLHttpRequest)
十分相似,但本文无意详细讲解缘起于 Js 新标准的Fetch
使用方法,读者可前往由 mozilla 基金会构建的 MDN Web Docs 进行学习:Using Fetch
Making requests - 发起请求
若要从任何网址获取数据,仅需将URL
作为参数传入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',
}),
});
请阅读 Fetch Request docs 以获取完整的 Fetch 参数列表。
Handling the response - 解析服务器响应数据
在上面的示例中演示了如何发起请求。与此同时,你亦需要知道如何接受解析服务器返回的响应数据。
网络通信的本质是一种异步请求,Fetch 方法将返回一种名为Promise的对象,这种模式将极大的简化异步请求操作代码(译者注:其极大的改变了往常的 callback 回调写法)
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 应用中使用 ES7 标准中的 async/await 语法(译者注:网络请求的异步本质无法变更):
async function getMoviesFromApi() {
try {
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
可能抛出的异常,否则请求出错时你无法看到任何报错及警告。
默认情况下,iOS 会阻止所有非 https(SSL 加密)请求。如果你请求的接口是 http 协议,那么首先需要添加一个
App Transport Security
的例外,如果您事先知道需要访问的域名,那么仅为这些域名添加例外情况会更安全; 如果域名并不确定,则可以完全禁用ATS
。 不过请注意,从 2017 年 1 月起,苹果的App Store
审查将需要合理的理由来禁用 ATS。 有关更多信息,请参阅Apple 的文档。
使用其他的网络通信库
React Native
中已经内置了XMLHttpRequest API(ajax)
。一些基于XMLHttpRequest
封装的第三方库也可以使用,例如frisbee
或是axios
等。(但注意不能使用 jQuery,因为 jQuery 中还使用了很多浏览器中才有而 RN 中没有的东西)。
var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
}
ss;
if (request.status === 200) {
console.log('success', request.responseText);
} else {
console.warn('error');
}
};
request.open('GET', 'https://mywebsite.com/endpoint/');
request.send();
react-native 中的安全机制与 web 开发并不相同,并不存在请求的跨域问题。
WebSocket Support - WebSocket 支持
React Native 亦支持WebSockets,一种基于 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);
};
s;
High Five!
If you've gotten here by reading linearly through the tutorial, then you are a pretty impressive human being. Congratulations. Next, you might want to check out all the cool stuff the community does with React Native.