大部分的app都需要进行网络连接,通过网络获取服务器的数据,然后更新app的界面展示内容,React-Native自然拥有网络的相关操作.官方文档
fetch
fetch('https://mywebsite.com/endpoint/')
自定义请求的方法,请求头,请求体
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
异步
使用then
fetch('https://mywebsite.com/endpoint.php')
.then((response) => response.text())
.then((responseText) => {
console.log(responseText);
})
.catch((error) => {
console.warn(error);
});
使用 async/await
在异步函数中调用
async getUsersFromApi() {
try {
let response = await fetch('https://mywebsite.com/endpoint/');
return response.users;
} catch(error) {
throw error;
}
}
WebSocket
websocket
XMLHttpRequest
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();
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
Image,
TouchableOpacity,
ToastAndroid,
Alert,
} = React;
var AwesomeProject = React.createClass({
getByFetch : function(){
fetch('https://m.baidu.com' )
.then((response) => response.text())
.then((responseText) => {
ToastAndroid.show(responseText, ToastAndroid.SHORT);
console.warn(new Date().getMilliseconds());
})
.catch((error) => {
console.warn(error);
}).done();
console.warn('请求是异步的:'+new Date().getMilliseconds());
},
getByXMLHttpRequest : function(){
var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
}
if (request.status === 200) {
ToastAndroid.show('success'+ request.responseText ,ToastAndroid.SHORT);
} else {
console.warn('error');
}
};
request.open('GET', 'https://m.baidu.com');
request.send();
},
postSource: function(){
fetch('https://m.baidu.com' )
.then((response) => response.text())
.then((responseText) => {
// Works on both iOS and Android
Alert.alert(
'请求结果',
responseText.substring(0,100),
[
{text: 'Ask me later', onPress: () => console.warn('Ask me later pressed')},
{text: 'Cancel', onPress: () => console.warn('Cancel Pressed'), style: 'cancel'},
{text: 'OK', onPress: () => console.warn('OK Pressed')},
]
)
})
.catch((error) => {
console.warn(error);
}).done();
},
render: function() {
return (
<View style={{flex:1, justifyContent:'center', alignItems:'center' }}>
<TouchableOpacity onPress={this.getByFetch} style={ styles.button }>
<Text >GET by fetch</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.getByXMLHttpRequest} style={ styles.button }>
<Text >GET by XmlHttpRequest</Text>
</TouchableOpacity>
<TouchableOpacity onPress= { this.postSource } style={ styles.button }>
<Text >POST</Text>
</TouchableOpacity>
</View>
);
}
});
var styles = StyleSheet.create({
button: {
width : 180,
height: 50,
justifyContent:'center',
backgroundColor: '#e2e2e2',
alignItems:'center',
margin: 10,
}
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);