ReactNative-网络请求

ReactNative网络请求这部分很简单但也很重要只要知道web页面网络请求,这边也完全适应。这里通过代码家API结合ListView的使用来简单试用下fetch的get请求。

get请求

先看效果图
这里写图片描述

使用基本步骤:下面会贴出完整代码
1.在构造方法中初始化

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

2.通过componentDidMount()方法调用fetch加载数据并通过setState()方法刷新界面

    /**
     * 加载耗时操作
     */
    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();
    }

3.重写renderRow()方法进行界面绘制

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

            </View>
        )
    }

完整代码:

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;

Post请求

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  })
})

这个博客将网络请求封装了一下可以参考下,你也就不必这么麻烦了

http://blog.csdn.net/u010046908/article/details/50916511

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值