RN 的 fetch 组件网络请求

一 .网络基础

创建一个.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(
            <View style={styles.container}>
                <TouchableOpacity onPress={getRequest.bind(this,"http://project.lanou3g.com/projects/bj/reactnative/login.php?username=niu&password=1234")}>
                     <View style={styles.btn}>
                        <Text>GET</Text>
                     </View>
                </TouchableOpacity>
                <TouchableOpacity onPress={PostRequest.bind(this,"http://project.lanou3g.com/projects/bj/reactnative/login.php")}>
                    <View style={styles.btn}>
                        <Text>POST</Text>
                    </View>
                </TouchableOpacity>
            </View>

        );
    }
});



/*
* 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;



二 . 结合ListView 使用

在 .js文件中



import React, {Component} from 'react';
import {
    AppRegistry,
    StyleSheet,
    View,
    Text,
    TouchableOpacity,
    ToastAndroid,
    Image,
    ListView,
} from 'react-native';
Dimensions = require('Dimensions');
width = Dimensions.get('window').width;
height = Dimensions.get('window').height;

class FetchG extends Component {

    /**
     * 初始化数据
     */
    constructor(props) {
        super(props);
        this.state = {
            dataSource: new ListView.DataSource({
                rowHasChanged: ((row1, row2) => row1 !== row2)
            }),
            load: false
        }
    }

    /**
     * 渲染界面
     */
    render() {
        /**
         * 因为数据时异步加载, 用load判断是否正在加载 如果加载完毕重新刷新界面改变load值
         */
        if (!this.state.load) {
            return <Text>加载中...</Text>
        }

        return (this.renderView(this.state.dataSource))
    }


    renderView() {
        return (
            <ListView
                dataSource={this.state.dataSource}
                renderRow={this.renderRow}
            />
        )

    }

    /**
     * 重写renderRow
     */
    renderRow(rowData) {
        return (
            <View style={{ flex: 1 }}>
                <Image source={{ uri: rowData.url }}
                       style={{ width: width, height: height / 2, marginTop: 5 }}
                />

            </View>
        )
    }


    /**
     * 加载耗时操作
     */
    componentDidMount() {
        this.getDataFromFetch();
    }

    getDataFromFetch() {

        fetch('http://gank.io/api/search/query/listview/category/福利/count/10/page/1')//请求地址
            .then((response) => response.json())//取数据
            .then((responseText) => {//处理数据
                //通过setState()方法重新渲染界面
                this.setState({
                    //改变加载ListView
                    load: true,
                    //设置数据源刷新界面
                    dataSource: this.state.dataSource.cloneWithRows(responseText.results),
                })

            })
            .catch((error) => {
                console.warn(error);
            }).done();
    }
}
module.exports = FetchG;
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小毅哥哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值