React-Native 网络请求

/**

  • Sample React Native App
  • https://github.com/facebook/react-native
  • @flow
  • 感谢东方耀老师:http://bbs.reactnative.cn/user/%E4%B8%9C%E6%96%B9%E8%80%80
    */

'use strict';
'use strict';

import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
PixelRatio,
Text,
Alert,
TouchableHighlight,
TouchableOpacity,
TouchableWithoutFeedback,
ToastAndroid,
View
} from 'react-native';

var onePT = 1 / PixelRatio.get();

class MyFirstProject extends Component {

getByFetch() {
fetch('https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json')
.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() {
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() {
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() {

return (

  


    
      getByFetch


    


    
      getByXMLHttpRequest

    


    
      postSource

    

  

);

}

show(txt) {
alert(txt);
}
}

const styles = StyleSheet.create({

flex: {
flex: 1,
marginTop: 25,
alignItems: 'center',
justifyContent: 'center',
},

item: {
fontSize: 18,
color: '#434343',
marginLeft: 5,
marginTop: 10,
},

});
AppRegistry.registerComponent('MyFirstProject', () => MyFirstProject);

你可能感兴趣的:(React-Native 网络请求)