(
问渠那得清如许,为有源头活水来。
双手奉上RN官网)
Networking: 网络交互
- 使用Fetch
①发起请求
fetch('https://mywebsite.com/endpoint/', {
//请求方式
method: 'POST',
//指定一些请求头信息
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
//指定一些请求体信息
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
②处理响应:默认异步网络操作,不要忘了捕获处理异常,否则静默丢掉
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);
});
}
或者使用ES2017 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);
}
}
- 内置XMLHttpRequest API,从而可以直接使用它或者基于它的第三方库
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
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);
};