创建一个.js 文件
import React, {Component} from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity
} from 'react-native';
/*
* 在 ReactNative 中,使用 fetch 实现网络请求. fetch 同 XMLHttpRequest 非常类似,是一个封装程度更高的网络 API, 使用起来很简洁,因为使用了 Promise.
*
* Promise 是异步编程的一种解决方案,比传统的解决方案 -- 回调函数事件 -- 更合理和更强大, ES6将其写进了语言标准,统一了用法,原生提供了 Promise 对象,简单说就是一个容器,里面保存着整个未来才会起结束的事件(通常是一个异步操作)的结果
*
* Promise 对象代表一个异步操作,有三种状态: Pending(进行中), Resolved(已完成), Rejected(已失败).
*
* Promise 实例生成之后,可以分别指定"完成"和"失败"状态的回调函数.实现方式:链式调用方法.
* fetch 中使用的就是该特性.
*
* 语法:
* fetch(参数)
* .then(完成的回调函数)
* .catch(失败的回调函数)
*
* fetch(url, opts)
* .then((response) => {
* //网络请求成功执行改回调函数,得到响应对象,铜通过 response 可以获取请求的数据
* //例如: json,text 等等
*
* return response.text();
* //return response.json();
* })
*
* .then((resonseData) => {
* //处理请求得到的数据
*
* })
* .catch((error) => {
* //网络请求失败执行该回调函数,得到错误信息
*
* })
*
*
* */
function getRequest(url) {
var opts = {
method:"GET"
}
fetch(url, opts)
.then((response) =>{
return response.text(); //返回一个带有文本对象
})
.then((responseText) => {
alter(responseText);
})
.catch((error) => {
alter(error);
})
}
var GetData = React.createClass({
render:function () {
return(
GET
POST
);
}
});
/*
* FormData
*
* Web 应用中频繁使用的一项功能就是表单数据的序列化, XMLHttpRequest2级定义了 FormData 类型.
* FormData 主要用于实现序列化表单以及创建与表单格式相同的数据
*
* var data = new FormData();
* data.append("name", "yihuiyun");
* append 方法接收两个参数:;链和值.分别对应表单字段和字段中包含的值,添加多个键值对.
*
* 在 jquery 中,"key1=value1&key2=value2"作为参数传入对象框架会自动封装成 FormData 形式
* 在 Fetch 中进行 post 请求时,需要自动创建FormData 对象传给 body
* */
function PostRequest(url) {
//将"key1=value1&key2=value2"封装成 FormData 形式
let formData = new FormData();
formData.append("username","niu");
formData.append("password","1234");
var opts = {
method:"POST",
body:formData
}
fetch(url, opts)
.then((response) =>{
return response.text(); //返回一个带有文本对象
})
.then((responseText) => {
alter(responseText);
})
.catch((error) => {
alter(error);
})
}
var styles = StyleSheet.create({
container:{
flex:1,
marginTop:30,
backgroundColor:"cyan",
flexDirection:"row",
justifyContent:"center",
alignItems:"center"
},
btn:{
width:60,
height:30,
borderWidth:1,
borderRadius:3,
backgroundColor:"yellow",
borderColor:"black",
justifyContent:"center",
alignItems:"center"
}
});
module.exports = GetData;