前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >RN请求豆瓣数据

RN请求豆瓣数据

作者头像
IT架构圈
发布2018-05-31 15:49:48
9930
发布2018-05-31 15:49:48
举报
文章被收录于专栏:IT架构圈IT架构圈

此文适合react-native新手学习使用,侧重点在于Fetch网络请求、ListView数据源配置及展示。

项目中使用豆瓣网提供的开放数据接口 http://www.jianshu.com/p/c5160fda1d38

Util工具类封装 Util工具类封装了获取设备屏幕宽高、网络请求成功或者失败回调函数、数据请求成功前的等待效果.

代码语言:javascript
复制
/*
工具类
*/
import React, { Component} from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Dimensions, //用于获取设备屏幕的宽高
  ActivityIndicator
} from 'react-native';
var Util = {
  //屏幕尺寸
  windowSize: {
    width: Dimensions.get("window").width,
    height:Dimensions.get("window").height
  },
  getRequest: function(url,successCallback, failCallback) {
    fetch(url)
    .then((response) => response.json())
    .then((responseData) => successCallback(responseData))
    .catch((error) => failCallback(error));
  },
// loading效果
  loading:<ActivityIndicator style={{marginTop: 200}}/>
}
module.exports = Util;

数据请求部分

代码语言:javascript
复制
  getData: function() {
    this.setState({
      show: false
    });
    // 请求数据
    var that = this;
    //https://api.douban.com/v2/book/search?count=20&q=react
    var url = ServiceURL.book_search + "?count=20&q=" + this.state.keywords;
    Util.getRequest(url,function(data){
      // 请求成功回调
      if (!data.books || data.books.length == 0) {
        return alert("未查询到相关书籍")
      }
      var ds = new ListView.DataSource({
        rowHasChanged: (oldRow, newRow) => oldRow!==newRow
      });
      that.setState({
        show: true,
        dataSource: ds.cloneWithRows(data.books)
      });
    }, function(error){
      // 请求失败回调
      alert(error);
    })
  },

Demo下载地址 GitHub下载地址:https://github.com/dangxiaoyin/react-native-douban

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-03-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 编程坑太多 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档