zoukankan      html  css  js  c++  java
  • React-Native 之 GD (十八)监听 TabBarItem 点击与传值实现 点击 Item 进行刷新功能

    监听 TabBarItem 点击与传值实现 点击 Item 进行刷新功能

    原版 APP 中当我们点击 首页和海淘 2个 Item 时,会马上获取最新数据个数然后进行更新,这边来实现一下这个功能。

    1.通过通知的方式监听Item点击做相应的操作,所以我们在需要接收通知的页面注册一下通知,在需要的地方发送通知即可:

    步骤一:在 home 界面注册通知

    // 组件加载完成
    componentDidMount() {
        // 注册通知
        this.subscription = DeviceEventEmitter.addListener('clickHomeItem', () => this.clickTabBarItem());
    }
    

    步骤二:在页面销毁之前记得注销下:

    componentWillUnmount() {
        // 注销通知
        this.subscription.remove();
    }
    

    步骤三:clickTabBarItem 方法逻辑: 

    // 点击了Item
    clickTabBarItem() {
        // 加载最新数据
        this.loadData();
    }
    

    2.回到 Main 页面,我们修改下点击 Item 响应的事件:

    步骤一:修改 Item 点击事件:

    onPress={() => this.clickItem(selectedTab, subscription)}>
    

    步骤二:clickItem 方法逻辑:

    // 点击了Item
    clickItem(selectedTab, subscription) {
    
        if (subscription !== "" && this.state.selectedTab == selectedTab) {
            // 发送通知
            DeviceEventEmitter.emit(subscription);
        }
    
        // 渲染页面
        this.setState({ selectedTab: selectedTab })
    }
    

    步骤三:所以传值也需要新增 subscription 参数,不需要订阅的按钮就可以传 "" 即可。

    每次点击 Item 获取到最新数据后我们需要及时更新 Item 角标

    实现思路很简单,我们使用逆传的方式,每次获取到最新数据的时候,同时需要调用一下 在 main 中 获取最新数据个数 的请求方法即可。

    步骤一:首先我们在 home 定义一个属性供外界使用:

    static defaultProps = {
        loadDataNumber:{},   // 回调
    };

    步骤二:接着,当我们请求到最新数据的同时,我们调用一下这个属性,就可以了:

    // 获取最新数据个数
    this.loadDataNumber();
    
    // loadDataNumber 中的逻辑
    loadDataNumber() {
        // 调用 this.props.loadDataNumber 中保存的代码块
        this.props.loadDataNumber();
    }

    步骤三:为了方便调用,我们将 获取最新数据个数 的逻辑抽出来放到单独的方法内,这边顺便再介绍 AsyncStorage 怎么同时获取多个 key 值的方法:

    // 获取最新数据个数网络请求
    loadDataNumber() {
        // 取出id
        AsyncStorage.multiGet(['cnfirstID', 'usfirstID'], (error, stores) => {
            // 拼接参数
            let params = {
                "cnmaxid" : stores[0][1],
                "usmaxid" : stores[1][1],
            };
    
            // 请求数据
            HTTPBase.get('http://guangdiu.com/api/getnewitemcount.php', params)
                .then((responseData) => {
                    this.setState({
                        cnbadgeText:responseData.cn,
                        usbadgeText:responseData.us
                    })
                })
                .catch((error) => {
    
                })
        });
    }
    

    步骤四:很好,接着我们转到 main 中,修改下 renderTabBarItem 方法中的内容,实现一下 “ 属性的方法:

    renderScene={(route, navigator) => {
        let Component = route.component;
        return <Component {...route.params}
            	navigator={navigator}
            	loadDataNumber={() => this.loadDataNumber()} />
    }}
    

      

    一键置顶功能

    这个功能实现更加简单,只要我们调用 ScrollView 的 scrollTo 方法,将 y 设置为 0 即可;因为 ListView 是在 ScrollView 上进行的二次开发,所以它可以使用 ScrollView 的所有方法:

    // 点击了Item
    clickTabBarItem() {
        let PullList = this.refs.pullList;
        // 一键置顶
        PullList.scrollTo({y:0});
    }
    

    完整代码:

    GDMain.js

    /**
     * 主页面
     * 通过此文件连接其他文件
     */
    import React, {
        Component
    } from 'react';
    import {
        StyleSheet,
        Text,
        View,
        Image,
        Platform,
        DeviceEventEmitter,
        AsyncStorage,
    } from 'react-native';
    
    // tab组件(第三方框架)
    import TabNavigator from 'react-native-tab-navigator';
    // 导航器
    import CustomerComponents, {
        Navigator
    } from 'react-native-deprecated-custom-components';
    
    // 引入其他组件
    import Home from '../home/GDHome';
    import HT from '../ht/GDHt';
    import HourList from '../hourList/GDHourList';
    // 引入 HTTP封装组件
    import HTTP from '../http/HTTPBase';
    
    // 引入 本地数据存储封装组件 (数据持久化)
    // import RealmStorage from '../storage/realmStorage';
    
    export default class GD extends Component {
        // ES6
        // 构造
        constructor(props) {
            super(props);
            // 初始状态
            this.state = {
                selectedTab: 'home',    // 首选页面
                isHiddenTabBar:false,   // 是否隐藏tabbar
                cnbadgeText:'',         // 首页Item角标文本
                usbadgeText:'',         // 海淘Item角标文本
            };
        }
    
        // 获取最新数据个数网络请求
        loadDataNumber() {
            // 取出id
            AsyncStorage.multiGet(['cnfirstID','usfirstID'],(error, stores) => {
                // 拼接参数
                let params = {
                    "cnmaxid" : stores[0][1],
                    "usmaxid" : stores[1][1]
                };
    
                // 请求数据
                HTTPBase.get('http://guangdiu.com/api/getnewitemcount.php', params)
                    .then((responseData) => {
                        // 修改 状态值
                        this.setState({
                            cnbadgeText:responseData.cn,
                            usbadgeText:responseData.us
                        })
                    })
                    .catch((error) => {
    
                    })
            });
        }
    
        // 设置 Navigator 转场动画
        setNavAnimationType(route) {
            if(route.animationType) {    // 有值
                let conf = route.animationType;
                conf.gestures = null;    // 关闭返回手势
                return conf;
            }else{
                return Navigator.SceneConfigs.PushFromRight;  // 默认转场动画
            }
        }
    
        // 隐藏 TabBar
        hiddenTabBar(data) {
            this.setState({
                isHiddenTabBar:data,
            })
        }
    
        // 点击了Item
        clickItem(selectedTab, subscription) {
            if(subscription !== "" && this.state.selectedTab == selectedTab){
                // 发送通知
                DeviceEventEmitter.emit(subscription);
            }
            // 渲染页面
            this.setState({selectedTab: selectedTab})
        }
    
        // 返回 TabBar 的 Item
        renderTabBarItem(title, selectedTab, image, selectedImage, component, badgeText, subscription) {
            return (
                <TabNavigator.Item
                    selected={this.state.selectedTab === selectedTab}
                    badgeText={badgeText == 0 ? '' : badgeText}  // 角标
                    title={title}
                    selectedTitleStyle={{color:'black'}}
                    renderIcon={() => <Image source={{uri:image}} style={styles.tabbarIconStyle} />}
                    renderSelectedIcon = {() => <Image source={{uri:selectedImage}} style={styles.tabbarIconStyle} />}
                    onPress = {() => this.clickItem(selectedTab, subscription)}>
                    <Navigator
                    // 设置路由
                    initialRoute = {
                        {
                            name: selectedTab,
                            component: component
                        }
                    }
    
                    // 设置导航动画
                    configureScene={(route) => this.setNavAnimationType(route)}
    
                    renderScene = {
                        (route, navigator) => {
                            let Component = route.component;
                            return <Component
                                        {...route.params}
                                        navigator={navigator}
                                        loadDataNumber={() => this.loadDataNumber()}
                                    />
                        }
                    } />    
                </TabNavigator.Item>
            );
        }
    
        // 组件加载完成
        componentDidMount() {
            // 注册通知
            this.subscription = DeviceEventEmitter.addListener('isHiddenTabBar', (data)=>{this.hiddenTabBar(data)});
    
            // 最新数据的个数
            setInterval(() => {
                this.loadDataNumber();
            },3000)
        }
    
        // 组件即将销毁
        componentWillUnmount() {
            // 销毁
            this.subscription.remove();
        }
    
        render() {
            return (
                <TabNavigator
                    tabBarStyle={this.state.isHiddenTabBar !== true ? {} : {height:0, overflow:'hidden'}}
                    sceneStyle={this.state.isHiddenTabBar !== true ? {} : {paddingBottom:0}}
                >
                    { /* 首页 */ }
                    {this.renderTabBarItem("首页", 'home', 'tabbar_home_30x30', 'tabbar_home_selected_30x30', Home, this.state.cnbadgeText, "clickHomeItem")} 
                    { /* 海淘 */ } 
                    {this.renderTabBarItem("海淘", 'ht', 'tabbar_abroad_30x30', 'tabbar_abroad_selected_30x30', HT, this.state.usbadgeText, "clickHTItem")}
                    { /* 小时风云榜 */ }
                    {this.renderTabBarItem("小时风云榜", 'hourlist', 'tabbar_rank_30x30', 'tabbar_rank_selected_30x30', HourList)} 
                </TabNavigator>
            );
        }
    }
    
    const styles = StyleSheet.create({
        container: {
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: '#F5FCFF',
        },
        tabbarIconStyle: {
             Platform.OS === 'ios' ? 30 : 25,
            height: Platform.OS === 'ios' ? 30 : 25,
        }
    });

    GDHome.js

    /**
     * 首页
     */
    import React, { Component, PropTypes } from 'react';
    import {
        StyleSheet,
        Text,
        View,
        TouchableOpacity,
        Image,
        ListView,
        Dimensions,
        ActivityIndicator,
        Modal, // 模态
        AsyncStorage, // 缓存数据库(数据持久化)
        DeviceEventEmitter, // 通知
        InteractionManager, // 解决跳转卡顿问题
    } from 'react-native';
    
    // 引入 下拉刷新组件
    import {PullList} from 'react-native-pull';
    // 导航器
    import CustomerComponents, {
        Navigator
    } from 'react-native-deprecated-custom-components';
    
    // 获取屏幕宽高
    const {width, height} = Dimensions.get('window');
    
    // 引入自定义导航栏组件
    import CommunalNavBar from '../main/GDCommunalNavBar';
    // 引入 公共cell
    import CommunalCell from '../main/GDCommunalCell';
    // 引入 详情页 组件
    import CommunalDetail from '../main/GDCommunalDetail';
    // 引入 筛选菜单组件
    import CommunalSiftMenu from '../main/GDCommunalSiftMenu';
    // 引入 近半小时热门组件
    import HalfHourHot from './GDHalfHourHot';
    // 引入 搜索页面组件
    import Search from '../main/GDSearch';
    // 引入 空白页组件
    import NoDataView from '../main/GDNoDataView';
    
    // 数据 筛选菜单
    import HomeSiftData from '../data/HomeSiftData.json';
    
    export default class GDHome extends Component {
        
        // 初始化(默认)
        static defaultProps = {
            loadDataNumber:{} // 回调
        }
    
        // 构造
        constructor(props) {
            super(props);
            // 初始状态
            this.state = {
                dataSource: new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}), // 数据源 优化
                loaded: false, // 用于判断是否显示空白页
                isHalfHourHotModal: false, // 用于判断模态的可见性
                isSiftModal: false, // 筛选功能
            };
            // 全局定义一个空数组用于存储列表数据
            this.data = [];
            // 绑定
            this.loadData = this.loadData.bind(this);
            this.loadMore = this.loadMore.bind(this);
        }
    
        // 加载最新数据网络请求
        loadData(resolve) {
    
            let params = {"count" : 10 };
    
            HTTPBase.get('https://guangdiu.com/api/getlist.php', params)
                .then((responseData) => {
    
                    // 情况数组(刷新时)
                    this.data = [];
    
                    // 拼接数据
                    this.data = this.data.concat(responseData.data);
    
                    // 重新渲染
                    this.setState({
                        dataSource: this.state.dataSource.cloneWithRows(this.data),
                        loaded:true,
                    });
    
                    // 关闭刷新动画
                    if (resolve !== undefined){
                        setTimeout(() => {
                            resolve();
                        }, 1000);
                    }
    
                    // 获取最新数据个数(角标)
                    this.loadDataNumber();
    
                    // 存储数组中最后一个元素的id
                    let cnlastID = responseData.data[responseData.data.length - 1].id;
                    AsyncStorage.setItem('cnlastID', cnlastID.toString());  // 只能存储字符或字符串
    
                    // 首页存储数组中第一个元素的id
                    let cnfirstID = responseData.data[0].id;
                    AsyncStorage.setItem('cnfirstID', cnfirstID.toString());
    
                    // // 清除本地存储的数据
                    // RealmBase.removeAllData('HomeData');
    
                    // // 存储数据到本地
                    // RealmBase.create('HomeData', responseData.data); // 向数据表存储数据
                })
                .catch((error) => {
                    // // 数据加载失败,拿到本地存储的数据,展示出来,如果没有存储,那就显示无数据页面
                    // this.data = RealmBase.loadAll('HomeData'); // 从数据表提取数据
    
                    // // 重新渲染
                    // this.setState({
                    //     dataSource: this.state.dataSource.cloneWithRows(this.data),
                    //     loaded:true,
                    // });
                })
        }
    
        // 加载更多数据的网络请求
        loadMoreData(value) {
    
            let params = {
                "count" : 10,
                "sinceid" : value 
            };
    
            HTTPBase.get('https://guangdiu.com/api/getlist.php', params)
                .then((responseData) => {
    
                    // 拼接数据
                    this.data = this.data.concat(responseData.data);
    
                    // 重新渲染
                    this.setState({
                        dataSource: this.state.dataSource.cloneWithRows(this.data),
                        loaded:true,
                    });
    
                    // 存储数组中最后一个元素的id
                    let cnlastID = responseData.data[responseData.data.length - 1].id;
                    AsyncStorage.setItem('cnlastID', cnlastID.toString());  // 只能存储字符或字符串
    
                })
                .catch((error) => {
    
                })
        }
    
        // 加载筛选数据网络请求
        loadSiftData(mall, cate) {
    
            let params = {};
    
            if(mall === "" && cate === ""){  // 全部
                this.loadData(undefined);
                return;
            }
    
            if(mall === ""){ // cate 有值
                params = {
                    "cate" : cate
                };
            }else{
                params = {
                    "mall" : mall
                };
            }
    
            HTTPBase.get('https://guangdiu.com/api/getlist.php', params)
                .then((responseData) => {
    
                    // 情况数组(刷新时)
                    this.data = [];
    
                    // 拼接数据
                    this.data = this.data.concat(responseData.data);
    
                    // 重新渲染
                    this.setState({
                        dataSource: this.state.dataSource.cloneWithRows(this.data),
                        loaded:true,
                    });
    
                    // 存储数组中最后一个元素的id
                    let cnlastID = responseData.data[responseData.data.length - 1].id;
                    AsyncStorage.setItem('cnlastID', cnlastID.toString());  // 只能存储字符或字符串
                })
                .catch((error) => {
    
                })
        }
    
        // 获取最新数据个数
        loadDataNumber() {
            this.props.loadDataNumber();
        }
    
        // 加载更多数据操作
        loadMore() {
            // 读取存储的id
            AsyncStorage.getItem('cnlastID')
                .then((value) => {
                    // 数据加载操作
                    this.loadMoreData(value);
                })
        }
    
        // 模态到近半小时热门
        pushToHalfHourHot() {
            this.setState({
                isHalfHourHotModal: true
            })
        }
    
        // 跳转到搜索页面
        pushToSearch() {
            InteractionManager.runAfterInteractions(() => {
                this.props.navigator.push({
                    component: Search,
                });
            });
        }
    
        // 安卓模态销毁模态
        onRequestClose() {
            this.setState({
                isHalfHourHotModal:false,
                isSiftModal:false,
            })
        }
    
        // 关闭模态
        closeModal(data) {
            this.setState({
                isHalfHourHotModal:data,
                isSiftModal:data,
            })
        }
    
        // 显示筛选菜单
        showSiftMenu() {
            this.setState({
                isSiftModal:true,
            })
        }
    
        // 跳转到详情页
        pushToDetail(value) {
            InteractionManager.runAfterInteractions(() => {
                this.props.navigator.push({
                    component:CommunalDetail,
                    params: {
                        url: 'https://guangdiu.com/api/showdetail.php' + '?' + 'id=' + value
                    }
                });
            });
        }
    
        // 点击了Item
        clickTabBarItem() {
            // 一键置顶
            this.refs.pullList.scrollTo({y:0});
        }
    
        // 返回左边按钮
        renderLeftItem() {
            // 将组件返回出去
            return(
                <TouchableOpacity
                    onPress={() => {this.pushToHalfHourHot()}}
                >
                    <Image source={{uri:'hot_icon_20x20'}} style={styles.navbarLeftItemStyle} />
                </TouchableOpacity>
            );
        }
    
        // 返回中间按钮
        renderTitleItem() {
            return(
                <TouchableOpacity
                    // 显示或隐藏筛选菜单
                    onPress={() => {this.showSiftMenu()}}
                >
                    <Image source={{uri:'navtitle_home_down_66x20'}} style={styles.navbarTitleItemStyle} />
                </TouchableOpacity>
            );
        }
    
        // 返回右边按钮
        renderRightItem() {
            return(
                <TouchableOpacity
                    // 跳转搜索页面 
                    onPress={() => {this.pushToSearch()}}
                >
                    <Image source={{uri:'search_icon_20x20'}} style={styles.navbarRightItemStyle} />
                </TouchableOpacity>
            );
        }
    
        // ListView尾部
        renderFooter() {
            return (
                <View style={{height: 100}}>
                    <ActivityIndicator />
                </View>
            );
        }
    
        // 返回每一行cell的样式
        renderRow(rowData) {
            // 使用cell组件
            return(
                <TouchableOpacity
                    // 给每一个cell添加点击事件
                    onPress={() => this.pushToDetail(rowData.id)}
                >
                    <CommunalCell
                        image={rowData.image}
                        title={rowData.title}
                        mall={rowData.mall}  // 平台
                        pubTime={rowData.pubtime}  // 时间
                        fromSite={rowData.fromsite}  // 来源
                    />
                </TouchableOpacity>
            );
        }
    
        // 根据网络状态决定是否渲染 listView
        renderListView() {
            if(this.state.loaded === false) {
                // 显示空白页
                return(
                    <NoDataView />
                );
            }else{
                return(
                    <PullList   // 将ListView 改为 PullList
                        ref="pullList"  // 一键置顶
                        // 下拉刷新
                        onPullRelease={(resolve) => this.loadData(resolve)}
                        // 数据源 通过判断dataSource是否有变化,来判断是否要重新渲染
                        dataSource={this.state.dataSource} 
                        renderRow={this.renderRow.bind(this)}
                        // 隐藏水平线
                        showsHorizontalScrollIndicator={false}
                        style={styles.listViewStyle}
                        initialListSize={7}  // 默认渲染数据条数
                        // 返回 listView 头部
                        renderHeader={this.renderHeader}
                        // 上拉加载更多
                        onEndReached={this.loadMore}
                        onEndReachedThreshold={60}
                        renderFooter={this.renderFooter}
                    />
                );
            }
        }
    
        // 组件加载完成
        componentDidMount() {
            // 刷新数据
            this.loadData();
    
            // 注册通知
            this.subscription = DeviceEventEmitter.addListener('clickHomeItem', () => this.clickTabBarItem())
        }
    
        render() {
            return (
                <View style={styles.container}>
                    {/* 初始化近半小时热门模态 */}
                    <Modal
                        animationType='slide'  // 动画 底部弹窗
                        transparent={false}  // 透明度
                        visible={this.state.isHalfHourHotModal}  // 可见性
                        onRequestClose={() => this.onRequestClose()}  // 销毁
                    >
                        <Navigator
                            initialRoute={{
                                name:'halfHourHot',
                                component:HalfHourHot
                            }}
    
                            renderScene={(route, navigator) => {
                                let Component = route.component;
                                return <Component
                                    removeModal={(data) => this.closeModal(data)}
                                    {...route.params}
                                    navigator={navigator} />
                            }} />
                    </Modal>
    
                    {/* 初始化筛选菜单模态 */}
                    <Modal
                        animationType='none'  // 无动画
                        transparent={true}  // 为透明状态
                        visible={this.state.isSiftModal}  // 可见性
                        onRequestClose={() => this.onRequestClose()}  // 销毁
                    >
                        <CommunalSiftMenu
                            removeModal={(data) => this.closeModal(data)}
                            data={HomeSiftData}
                            loadSiftData={(mall, cate) => this.loadSiftData(mall, cate)}
                        />
                    </Modal>
    
                    {/* 导航栏样式 */}
                    <CommunalNavBar
                        leftItem = {() => this.renderLeftItem()}
                        titleItem = {() => this.renderTitleItem()}
                        rightItem = {() => this.renderRightItem()}
                    />
    
                    {/* 根据网络状态决定是否渲染 listView */}
                    {this.renderListView()}
                </View>
            );
        }
    }
    
    const styles = StyleSheet.create({
        container: {
            flex: 1,
            alignItems: 'center',
        },
        navbarLeftItemStyle: {
            20,
            height:20,
            marginLeft:15,
        },
        navbarTitleItemStyle: {
            66,
            height:20,
        },
        navbarRightItemStyle: {
            20,
            height:20,
            marginRight:15,
        },
    
        listViewStyle: {
            width,
        },
    });

    GDHt.js

    /**
     * 海淘折扣
     */
    import React, { Component } from 'react';
    import {
        StyleSheet,
        Text,
        View,
        TouchableOpacity,
        Image,
        ListView,
        Dimensions,
        ActivityIndicator,
        Modal, // 模态
        AsyncStorage, // 缓存数据库(数据持久化)
        DeviceEventEmitter, // 通知
        InteractionManager, //  解决跳转卡顿问题
    } from 'react-native';
    
    // 引入 下拉刷新组件
    import {PullList} from 'react-native-pull';
    // 导航器
    import CustomerComponents, {
        Navigator
    } from 'react-native-deprecated-custom-components';
    
    // 获取屏幕宽高
    const {width, height} = Dimensions.get('window');
    
    // 引入自定义导航栏组件
    import CommunalNavBar from '../main/GDCommunalNavBar';
    // 引入 cell
    import CommunalCell from '../main/GDCommunalCell';
    // 引入 详情页 组件
    import CommunalDetail from '../main/GDCommunalDetail';
    // 引入 筛选菜单组件
    import CommunalSiftMenu from '../main/GDCommunalSiftMenu';
    // 引入 近半小时热门组件
    import USHalfHourHot from './GDUSHalfHourHot';
    // 引入 搜索页面组件
    import Search from '../main/GDSearch';
    // 引入 空白页组件
    import NoDataView from '../main/GDNoDataView';
    
    // 数据 筛选菜单
    import HTSiftData from '../data/HTSiftData.json';
    
    export default class GDHome extends Component {
    
        // 初始化(默认)
        static defaultProps = {
            loadDataNumber:{} // 回调
        }
    
        // 构造
        constructor(props) {
            super(props);
            // 初始状态
            this.state = {
                dataSource: new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}), // 数据源 优化
                loaded: false, // 用于判断是否显示空白页
                isUSHalfHourHotModal: false, // 用于判断模态的可见性
                isSiftModal: false, // 筛选功能
            };
            // 全局定义一个空数组用于存储列表数据
            this.data = [];
            // 绑定
            this.loadData = this.loadData.bind(this);
            this.loadMore = this.loadMore.bind(this);
        }
    
        // 加载最新数据网络请求
        loadData(resolve) {
    
            let params = {
                "count" : 10,
                "country" : "us"
            };
    
            HTTPBase.get('https://guangdiu.com/api/getlist.php', params)
                .then((responseData) => {
    
                    // 清空数组(刷新时)
                    this.data = [];
    
                    // 拼接数据
                    this.data = this.data.concat(responseData.data);
    
                    // 重新渲染
                    this.setState({
                        dataSource: this.state.dataSource.cloneWithRows(this.data),
                        loaded:true,
                    });
    
                    // 关闭刷新动画
                    if (resolve !== undefined){
                        setTimeout(() => {
                            resolve();
                        }, 1000);
                    }
    
                    // 获取最新数据个数(角标)
                    this.loadDataNumber();
    
                    // 存储数组中最后一个元素的id
                    let uslastID = responseData.data[responseData.data.length - 1].id;
                    AsyncStorage.setItem('uslastID', uslastID.toString());  // 只能存储字符或字符串
    
                    // 首页存储数组中第一个元素的id
                    let usfirstID = responseData.data[0].id;
                    AsyncStorage.setItem('usfirstID', usfirstID.toString());
                    
                    // // 清除本地存储的数据
                    // RealmBase.removeAllData('HomeData');
    
                    // // 存储数据到本地
                    // RealmBase.create('HomeData', responseData.data); // 向数据表存储数据
                })
                .catch((error) => {
                    // // 数据加载失败,拿到本地存储的数据,展示出来,如果没有存储,那就显示无数据页面
                    // this.data = RealmBase.loadAll('HomeData'); // 从数据表提取数据
    
                    // // 重新渲染
                    // this.setState({
                    //     dataSource: this.state.dataSource.cloneWithRows(this.data),
                    //     loaded:true,
                    // });
                })
        }
    
        // 加载更多数据的网络请求
        loadMoreData(value) {
    
            let params = {
                "count" : 10,
                "country" : "us",
                "sinceid" : value 
            };
    
            HTTPBase.get('https://guangdiu.com/api/getlist.php', params)
                .then((responseData) => {
    
                    // 拼接数据
                    this.data = this.data.concat(responseData.data);
    
                    // 重新渲染
                    this.setState({
                        dataSource: this.state.dataSource.cloneWithRows(this.data),
                        loaded:true,
                    });
    
                    // 存储数组中最后一个元素的id
                    let uslastID = responseData.data[responseData.data.length - 1].id;
                    AsyncStorage.setItem('uslastID', uslastID.toString());  // 只能存储字符或字符串
    
                })
                .catch((error) => {
    
                })
        }
    
        // 加载筛选数据网络请求
        loadSiftData(mall, cate) {
    
            let params = {};
    
            if(mall === "" && cate === ""){  // 全部
                this.loadData(undefined);
                return;
            }
    
            if(mall === ""){ // cate 有值
                params = {
                    "cate" : cate,
                    "country" : "us"
                };
            }else{
                params = {
                    "mall" : mall,
                    "country" : "us"
                };
            }
    
            HTTPBase.get('https://guangdiu.com/api/getlist.php', params)
                .then((responseData) => {
    
                    // 情况数组(刷新时)
                    this.data = [];
    
                    // 拼接数据
                    this.data = this.data.concat(responseData.data);
    
                    // 重新渲染
                    this.setState({
                        dataSource: this.state.dataSource.cloneWithRows(this.data),
                        loaded:true,
                    });
    
                    // 存储数组中最后一个元素的id
                    let cnlastID = responseData.data[responseData.data.length - 1].id;
                    AsyncStorage.setItem('cnlastID', cnlastID.toString());  // 只能存储字符或字符串
                })
                .catch((error) => {
    
                })
        }
    
        // 获取最新数据个数
        loadDataNumber() {
            this.props.loadDataNumber();
        }
    
        // 加载更多数据操作
        loadMore() {
            // 读取存储的id
            AsyncStorage.getItem('uslastID')
                .then((value) => {
                    // 数据加载操作
                    this.loadMoreData(value);
                })
        }
    
        // 模态到近半小时热门
        pushToHalfHourHot() {
            this.setState({
                isUSHalfHourHotModal: true
            })
        }
    
        // 跳转到搜索页面
        pushToSearch() {
            InteractionManager.runAfterInteractions(() => {
                this.props.navigator.push({
                    component: Search,
                });
            });
        }
    
        // 安卓模态销毁模态
        onRequestClose() {
            this.setState({
                isUSHalfHourHotModal:false,
                isSiftModal:false
            })
        }
    
        // 关闭模态
        closeModal(data) {
            this.setState({
                isUSHalfHourHotModal:data,
                isSiftModal:data
            })
        }
    
        // 显示筛选菜单
        showSiftMenu() {
            this.setState({
                isSiftModal:true,
            })
        }
    
        // 跳转详情页
        pushToDetail(value) {
            InteractionManager.runAfterInteractions(() => {
                this.props.navigator.push({
                    component:CommunalDetail,
                    params: {
                        url: 'https://guangdiu.com/api/showdetail.php' + '?' + 'id=' + value
                    }
                });
            });
        }
    
        // 点击了Item
        clickTabBarItem() {
            // 一键置顶
            this.refs.pullList.scrollTo({y:0});
        }
    
        // 返回左边按钮
        renderLeftItem() {
            // 将组件返回出去
            return(
                <TouchableOpacity
                    onPress={() => {this.pushToHalfHourHot()}}
                >
                    <Image source={{uri:'hot_icon_20x20'}} style={styles.navbarLeftItemStyle} />
                </TouchableOpacity>
            );
        }
    
        // 返回中间按钮
        renderTitleItem() {
            return(
                <TouchableOpacity
                    // 显示或隐藏筛选菜单
                    onPress={() => {this.showSiftMenu()}}
                >
                    <Image source={{uri:'navtitle_home_down_66x20'}} style={styles.navbarTitleItemStyle} />
                </TouchableOpacity>
            );
        }
    
        // 返回右边按钮
        renderRightItem() {
            return(
                <TouchableOpacity
                    // 跳转搜索页面 
                    onPress={() => {this.pushToSearch()}}
                >
                    <Image source={{uri:'search_icon_20x20'}} style={styles.navbarRightItemStyle} />
                </TouchableOpacity>
            );
        }
    
        // ListView尾部
        renderFooter() {
            return (
                <View style={{height: 100}}>
                    <ActivityIndicator />
                </View>
            );
        }
    
        // 返回每一行cell的样式
        renderRow(rowData) {
            // 使用cell组件
            return(
                <TouchableOpacity
                    // 给每一个cell添加点击事件
                    onPress={() => this.pushToDetail(rowData.id)}
                >
                    <CommunalCell
                        image={rowData.image}
                        title={rowData.title}
                        mall={rowData.mall}  // 平台
                        pubTime={rowData.pubtime}  // 时间
                        fromSite={rowData.fromsite}  // 来源
                    />
                </TouchableOpacity>
            );
        }
    
        // 根据网络状态决定是否渲染 listView
        renderListView() {
            if(this.state.loaded === false) {
                // 显示空白页
                return(
                    <NoDataView />
                );
            }else{
                return(
                    <PullList   // 将ListView 改为 PullList
                        ref="pullList"  // 一键置顶
                        // 下拉刷新
                        onPullRelease={(resolve) => this.loadData(resolve)}
                        // 数据源 通过判断dataSource是否有变化,来判断是否要重新渲染
                        dataSource={this.state.dataSource} 
                        renderRow={this.renderRow.bind(this)}
                        // 隐藏水平线
                        showsHorizontalScrollIndicator={false}
                        style={styles.listViewStyle}
                        initialListSize={7}
                        // 返回 listView 头部
                        renderHeader={this.renderHeader}
                        // 上拉加载更多
                        onEndReached={this.loadMore}
                        onEndReachedThreshold={60}
                        renderFooter={this.renderFooter}
                    />
                );
            }
        }
    
        // 组件加载完成
        componentDidMount() {
            // 加载最新数据
            this.loadData();
    
            // 注册通知
            this.subscription = DeviceEventEmitter.addListener('clickHTItem', () => this.clickTabBarItem())
        }
    
        render() {
            return (
                <View style={styles.container}>
                    {/* 初始化近半小时热门模态 */}
                    <Modal
                        animationType='slide'  // 动画 底部弹窗
                        transparent={false}  // 透明度
                        visible={this.state.isUSHalfHourHotModal}  // 可见性
                        onRequestClose={() => this.onRequestClose()}  // 销毁
                    >
                        <Navigator
                            initialRoute={{
                                name:'ushalfHourHot',
                                component:USHalfHourHot
                            }}
    
                            renderScene={(route, navigator) => {
                                let Component = route.component;
                                return <Component
                                    removeModal={(data) => this.closeModal(data)}
                                    {...route.params}
                                    navigator={navigator} />
                            }} />
                    </Modal>
    
                    {/* 初始化筛选菜单模态 */}
                    <Modal
                        animationType='none'  // 无动画
                        transparent={true}  // 为透明状态
                        visible={this.state.isSiftModal}  // 可见性
                        onRequestClose={() => this.onRequestClose()}  // 销毁
                    >
                        <CommunalSiftMenu
                            removeModal={(data) => this.closeModal(data)}
                            data={HTSiftData}
                            loadSiftData={(mall, cate) => this.loadSiftData(mall, cate)}
                        />
                    </Modal>
    
                    {/* 导航栏样式 */}
                    <CommunalNavBar
                        leftItem = {() => this.renderLeftItem()}
                        titleItem = {() => this.renderTitleItem()}
                        rightItem = {() => this.renderRightItem()}
                    />
    
                    {/* 根据网络状态决定是否渲染 listView */}
                    {this.renderListView()}
                </View>
            );
        }
    }
    
    const styles = StyleSheet.create({
        container: {
            flex: 1,
            alignItems: 'center',
        },
        navbarLeftItemStyle: {
            20,
            height:20,
            marginLeft:15,
        },
        navbarTitleItemStyle: {
            66,
            height:20,
        },
        navbarRightItemStyle: {
            20,
            height:20,
            marginRight:15,
        },
    
        listViewStyle: {
            width,
        },
    });

    .

  • 相关阅读:
    【原】【Git】EGit强制覆盖本地文件
    【EGit】The current branch is not configured for pull No value for key branch.master.merge found in config
    【转】【Egit】如何将eclipse中的项目上传至Git
    参加SAP VT项目有感
    2013_12_30 纪念
    2013 12 25 圣诞日
    gin系列-中间件
    gin系列- 路由及路由组
    gin系列-重定向
    gin系列-文件上传
  • 原文地址:https://www.cnblogs.com/crazycode2/p/7465255.html
Copyright © 2011-2022 走看看