ReactNative学习实例(三) 使用fetch获取网络数据

实例来自http://blog.csdn.net/u014360817/article/details/52447516


RN自带了一个非常优雅的网络操作库fetch,下面的这个例子从gankio的接口拿到了美女图片的url然后通过state 传给列表组件,列表里返回图片组件显示图片。网络数据获取方法写在componentDidMount中,这个方法是组件生命周期中需要调用的一个方法。

class AwesomeProject extends Component {// 初始化模拟数据


    constructor(props) {
        super(props);

        const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => {r1 !== r2}});
        this.state = {
            dataSource: ds,
            load:false,
            text:''
        };
    }

    //耗时操作放在这里面
    componentDidMount(){
        this.getNet();
    }

    getNet(){
        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();
    }

    render() {
        if(this.state.load){
            return (
                <View style={{flex: 1, paddingTop: 22}}>
                    <ListView
                        dataSource={this.state.dataSource}
                        renderRow={(rowData)=>
                            <View>
                                <Image
                                    style={{ width: 400, height: 250, marginTop: 5 }}
                                    source={{uri:rowData.url}}/>
                            </View>}
                        />
                </View>
            );
        } else{
            return(
                <View>
                    <Text>loading......</Text>
                </View>
            );
        }
    }
}

这里使用的是fetch的一个参数的方法,参数自然就是url,默认请求方式是GET,还有两个参数的方法,第二个参数是一组请求参数。执行fetch后返回一个Promise对象,通过then继续获取数据,这里response.json表示获取json格式的数据,也可以用text获取纯文本的数据。

获取到json后接下来就是解析json,这里的json里面有一个result数组,直接拿出来作为数据源的数据传入即可。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值