美文网首页ReactNative笔记
RN笔记-项目教程与源码分享

RN笔记-项目教程与源码分享

作者: 金丝楠 | 来源:发表于2017-02-24 17:31 被阅读513次

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

    项目中使用豆瓣网提供的开放数据接口

    Util工具类封装

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

    /*
    工具类
    */
    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;
    
    

    数据请求部分

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

    教程来源

    百度授课react-native零基础入门到项目实战:http://www.chuanke.com/v4702151-196697-1141970.html

    Demo下载地址

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

    附效果图

    Fetch请求效果图.gif

    相关文章

      网友评论

      • 夜3033:弱弱的问一句,我下载之后运行报React Base文件下一个错误,难道有什么我设置的不对嘛,我打开其他RN项目是可以运行的啊:disappointed_relieved:

      本文标题:RN笔记-项目教程与源码分享

      本文链接:https://www.haomeiwen.com/subject/mdvwwttx.html