RN笔记-Fetch网络请求和ListView展示

Util工具类封装:获取当前屏幕宽高、网络请求回调函数、Loading加载效果

RN笔记-Fetch网络请求和ListView展示_第1张图片
10.gif
/*
工具类
*/


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:
}


module.exports = Util;

Fetch请求和ListView展示:

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  ListView,
  ScrollView
} from 'react-native';


var Util = require("./../common/util");
var SearchBar = require("./../common/searchBar");
var ServiceURL = require("./../common/service");
var BookItem = require("./book_item");
var BookDetail = require("./book_detail");

var BookList = React.createClass({
  getInitialState: function() {
    var ds = new ListView.DataSource({
      rowHasChanged: (oldRow, newRow) => oldRow!==newRow
    });
    return {
      dataSource: ds,
      show: false,
      keywords: "React"
    };
  },

  _changeText: function(text) {
    this.setState({
      keywords: text
    });
  },

  _searchPress: function() {
    this.getData();
  },

  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);
    })
  },

_showDetail: function(bookID) {
  var detailRoute = {
    component: BookDetail,
    passProps: {
      bookID: bookID
    }
  }
  this.props.navigator.push(detailRoute);
},
  render: function() {
    return (
      
        
        {
          //请求数据时显示loading 数据请求成功后显示ListView
          this.state.show ?
          
          : Util.loading
        }
      
    );
  },
  componentDidMount: function() {
    this.getData();
  },
  _renderRow: function(book) {
    return 
  },
  _renderSeparator: function(sectionID:number, rowID:number) {
    var style = {
      height: 1,
      backgroundColor: "#CCCCCC"
    }
    return 
  }
});

var styles = StyleSheet.create({

});

module.exports = BookList;

你可能感兴趣的:(RN笔记-Fetch网络请求和ListView展示)