從0到1利用React-Native構(gòu)建百思不得姐(二)

如果感覺我寫的不錯,關(guān)注我,給個star哦!項(xiàng)目地址

如果遇到什么問題可以在評論區(qū)回復(fù),或者加QQ群397885169討論

前言

昨天終于把公司雙十二的項(xiàng)目上線了,才有了時(shí)間寫這第二篇文章,在上一篇中我們將項(xiàng)目的目錄結(jié)構(gòu)建好了,今天我們就來講一下網(wǎng)絡(luò)請求,首頁布局和cell頭部和尾部的布局。

網(wǎng)絡(luò)

俗話說:兵馬未動,糧草先行。子曰:”工欲善其事,必先利其器“。一款A(yù)pp如果沒有數(shù)據(jù),那只能是一個殼子,所以我們就先講一下網(wǎng)絡(luò)請求和請求封裝。
在第一篇中我說了,做百思不得姐最重要的一點(diǎn)就是有接口,我在做之前搜到了易源提供了百思不得姐的接口,第一眼看到的時(shí)候是很驚喜的,但真的調(diào)用過就會發(fā)現(xiàn),其中有好大的坑,讓我放棄它最主要的一點(diǎn)就是,調(diào)用圖片的時(shí)候,并沒有提供圖片的寬度和高度?。?!在百思不得姐中是有長圖,動圖和普通圖片之分的,如果沒有返回圖片的寬高,那圖片的布局就只能定死,頁面是很難看的,特別是長圖的時(shí)候。
如果在我的項(xiàng)目中有些接口數(shù)據(jù)不清楚的話,也可以對著易源提供的百思不得姐接口來看一下接口詳情。
最終的解決辦法就是找到了iOS大神,小碼哥老大李明杰曾講過的百思不得姐的接口。

網(wǎng)絡(luò)封裝

因?yàn)槭亲淼慕涌冢晕抑环庋b了get請求的部分,以后可能會有頁面用到post。
request.js

const Request = {
    get:(url, successCallBack , failCallBack) =>{
        console.log(url);
        return fetch(url)
            .then((response) => response.json())
            .then((response) => {
                successCallBack(response);
            })
            .catch ((error) => {
                failCallBack(error);
            });
    }
};

module.exports = Request;

網(wǎng)絡(luò)請求當(dāng)然最好是把網(wǎng)址什么的拆出去啦!因?yàn)闀簳r(shí)只用到首頁,其他頁面就沒有加在上面咯。
config.js

const Config = {
    api:{
        homeList:'http://api.budejie.com/api/api_open.php?a=list&c=data',
    },
};


module.exports = Config;

首頁

如果用過百思不得姐就會知道,它的首頁是一個不可滾動的類新聞應(yīng)用。但為了省事,我在這里使用了一個三方來實(shí)現(xiàn)了可以左右滾動的首頁。

首頁.png

homeContainer.js

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

import NavBar from 'react-native-navbar';
import ScrollableTabView, {DefaultTabBar, ScrollableTabBar} from 'react-native-scrollable-tab-view';
import HomeList from './homeList';

export default class homeContainer extends Component {
    constructor(props){
        super(props);
        this.state = {
            typeArr : [
                {'title':'全部', 'type':'1',},
                {'title':'視頻', 'type':'41',},
                {'title':'圖片', 'type':'10',},
                {'title':'段子', 'type':'29',},
                {'title':'聲音 ', 'type':'31',},
            ],
        }
    }
    render() {
        let titleConfig = {
            title: '百思不得姐',
            style: {color:'red',fontSize:20,fontWeight:'600'}
        };
        return (
            <View style={styles.container}>
                <NavBar
                    title={titleConfig}
                    style={{height:44,borderBottomWidth:1,borderBottomColor:'#dddddd'}}
                />
                <ScrollableTabView
                    renderTabBar={() => <ScrollableTabBar/>}
                    tabBarActiveTextColor='red'
                    tabBarInactiveTextColor='#rgb(67,67,67)'
                    tabBarBackgroundColor='#f7f7f7'

                    style={{height:10}}
                >
                    {
                        this.state.typeArr.map((item, i) => {
                            return (
                                <HomeList key={i} tabLabel={item.title} type={item.type}
                                          navigator={this.props.navigator} {...this.props}/>
                            )
                        })
                    }
                </ScrollableTabView>
            </View>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
});

首頁詳情

首頁的左右滾動效果已經(jīng)實(shí)現(xiàn)了,那么就要開始展示具體內(nèi)容了

首頁列表.png

homeList.js

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    ListView,
    InteractionManager,
    ActivityIndicator,
    RefreshControl
} from 'react-native';

import Config from '../../common/config';
import Request from '../../common/request';

import ListItem from './component/listItem';

let cacheResults = {
    items:[],
    allPage:0,
    maxId:'',
};
export default class homeList extends Component {

    constructor(props){
        super(props);
        let dataSource = new ListView.DataSource({rowHasChanged:(r1,r2) => r1 !== r2});
        this.state = {
            dataSource : dataSource,
            isRefreshing : false,
            isLoad: false,
            isLoadingMore:false,
            maxId: '',
        };
        this.renderRow = this.renderRow.bind(this);
        this.onRefresh = this.onRefresh.bind(this);
        this.onEndReached = this.onEndReached.bind(this);
        this.renderFooter = this.renderFooter.bind(this);
    }

    renderFooter(){

        if (!this.isMore()){
            console.log('1');
            return (
                <View style={styles.loadMoreStyle}>
                    <Text style={styles.loadMoreTextStyle} >沒有更多數(shù)據(jù)了</Text>
                </View>
            )
        }

        if (!this.state.isLoadingMore){
            return <View style={styles.loadMoreStyle} />
        }
        return(
            <ActivityIndicator
                style={styles.loadMoreStyle}
            />
        )
    }

    // 服務(wù)器有沒有更多數(shù)據(jù)
    isMore(){
        // 全部count等于整體count,那就說明結(jié)束了
        return cacheResults.items.count !== 2000;
    }

    // 加載更多數(shù)據(jù)
    onEndReached(){
        if (!this.isMore() || this.state.isLoadingMore ){
            return;
        }

        console.log(this.state.maxId);
        this.loadData(this.state.maxId);
    }

    // 下拉刷新
    onRefresh(){
        console.log(this.state.maxId);
        this.loadData(0);
    }
    // 跳轉(zhuǎn)頁面
    pushPage(rowData){
        let {navigator} = this.props;
        if (navigator) {
            InteractionManager.runAfterInteractions(()=> {
                navigator.push({
                    component: NewsDetail,
                    passProps:{
                        link:rowData.link,
                    }
                })
            });
        }
    }

    componentDidMount() {
        this.loadData(0);
    }

    loadData(maxtime){
        if (maxtime !== 0){
            this.setState({
                isLoadingMore:true
            });
        }else {
            this.setState({
                isRefreshing :true
            });
        }

        Request.get(Config.api.homeList + '&type='+ this.props.type +'&maxtime=' + maxtime ,(data)=>{
            console.log(data);
            let items = cacheResults.items.slice();
            let contentlist = data.list;

            if (maxtime !== 0){
                items = items.concat(contentlist);
                cacheResults.items = items;

            } else {
                items = contentlist;
                cacheResults.items = items;
            }
            cacheResults.allPage = data.info.page;

            this.setState({
                maxId:data.info.maxid
            });

            setTimeout(()=>{
                if (maxtime !== 0){
                    this.setState({
                        dataSource: this.state.dataSource.cloneWithRows(items),
                        isRefreshing:false,
                        isLoad:true,
                        isLoadingMore:false,
                    });
                } else {
                    this.setState({
                        dataSource: this.state.dataSource.cloneWithRows(items),
                        isLoad :true,
                        isRefreshing:false,
                        isLoadingMore:false,
                    });
                }
            },0);
        },(error)=>{
            console.log(error);
        });
    }
    renderRow(rowData){
        return(
            <ListItem itemData={rowData}/>
        )
    }
    render() {
        return (
            <View style={styles.container}>
                {
                    this.state.isLoad ?
                        <ListView
                            dataSource={this.state.dataSource}
                            renderRow={this.renderRow}
                            enableEmptySections={true}
                            onEndReached={this.onEndReached}
                            onEndReachedThreshold={40}
                            renderFooter={this.renderFooter}
                            refreshControl={
                                <RefreshControl
                                    refreshing={this.state.isRefreshing}
                                    onRefresh={this.onRefresh}
                                />
                            }
                        />
                        :
                        <ActivityIndicator
                            style={styles.loadDataStyle}
                        />
                }

            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5FCFF',
    },
    loadDataStyle: {
        marginVertical:20
    },
    loadMoreStyle:{
        marginVertical:20
    },
});

自定義Item

當(dāng)前的頁面中我只是簡單的展示了文字,而真正的圖片,頭像等我都沒有展示出來,接下來就是展示環(huán)節(jié)了。

導(dǎo)入組件

react-native-scrollable-tab-view 這個就是我們用來創(chuàng)建頂部滾動的控件啦!它還可以放在底部實(shí)現(xiàn)類似于安卓版微信那種的滾動tabBar;

吐槽

在列表頁中,我將上拉刷新和下拉加載都放在了一起,并沒有使用Redux。為什么呢?因?yàn)?,我之前在上一個項(xiàng)目中做實(shí)驗(yàn)的時(shí)候發(fā)現(xiàn),這種左右滾動的頁面,如果用Actions來管理網(wǎng)絡(luò),頁面的數(shù)組不好清空,我弄了大半天最后找了個折中的方式,將網(wǎng)絡(luò)請求放在Actions里面,將數(shù)據(jù)獲取又放回了List列表頁里面,我感覺如果那樣寫真的是不如一個頁面全都實(shí)現(xiàn)了,邏輯上也不是那么不清晰。
當(dāng)然,我會在之后的一些頁面中使用Redux,Redux并不是每個頁面都用才好!

我在使用react-native-scrollable-tab-view時(shí)想改變底部滾動條的顏色,發(fā)現(xiàn)調(diào)用它提供的方法竟然改不了!一起之下,我就殺進(jìn)了這個庫里面,直接改了部分源碼。

總結(jié)

現(xiàn)在用的這個接口用起來是有一點(diǎn)問題的。我在上拉加載更多的時(shí)候卡住了好久。
如果在使用中遇到什么問題,歡迎私信和評論哦!
如果喜歡我的文章,關(guān)注我,給個star哦!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,361評論 25 708
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,754評論 4 61
  • 如果感覺我寫的不錯,關(guān)注我,給個star哦!項(xiàng)目地址 如果遇到什么問題可以在評論區(qū)回復(fù),或者加QQ群3978851...
    掛著鈴鐺的兔閱讀 3,080評論 19 28
  • 這兩天都在家里呆著,做著各種家務(wù),四天多不在家,家里有些臟亂了,洗了好多衣服,又扔了一些東西,空間開始變大變干凈了...
    竺子閱讀 208評論 0 0
  • 《背影》 ——汪國真 背影,總是很簡單。簡單,是一種風(fēng)景。 ...
    宛宛魚閱讀 1,681評論 0 2

友情鏈接更多精彩內(nèi)容