React Native 多个列表共用一个ListView
来源:互联网 发布:pink ward知乎 编辑:程序博客网 时间:2024/06/03 14:43
多个列表共用一个ListView,导致切换Tab的时候,数据源没有及时切换,在下一个tab上面显示上一个tab的数据源。
多个列表共用一个ListView写法,数据源根据放入一个数组中,Tab切换的时候获取指定下标的数据源,状态机也是。
解决思路: 先置空数据源,然后再将数据源cloneWithRows, 因为我们本地状态机保存了dataArray数组。
本文只记录思路,很多是封装好的组件和一些头文件导入的不一样的方式
/** * Created by zhaung.haipeng on 2017/11/2. * Copyright (c) 2017, YUNXI. All rights reserved. * YUNXI PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */import React, { Component } from 'react';import { StyleSheet, View, Dimensions, InteractionManager, ListView, ActivityIndicator, TouchableOpacity, Alert, Platform, DeviceEventEmitter,} from 'react-native';import { ReactNavComponent, Widget, Util } from 'rn-yunxi';import AppWidget from '../../app-widget'import ScrollableTabView from 'react-native-scrollable-tab-view';const { width, height } = Dimensions.get('window');const { PrimaryHeader, DefaultTabBar, CommonSearchBar, Image, AlertCodeInput } = AppWidgetconst { Text, CommonListView, Button } = Widgetconst { DateUtil } = Utilimport OrderCommonCell from './OrderCommonCell';export default class OrderPage extends ReactNavComponent { constructor(props) { super(props); this.dataSource = Array(2).fill( new ListView.DataSource({ /*判断这两行是否相同,就是是否发生变化,决定渲染哪些行组件,避免全部渲染,提高渲染效率*/ rowHasChanged: (oldRow, newRow) => { return oldRow !== newRow } }) ); this.state = {//状态机变量声明, selectTab: 0, loading: true, listParams: Array(2).fill({ dataArray: [], listState: CommonListView.STATE_INIT, enableLoadMore: false, pageNum: 1, }), searchParams: Array(2).fill({ receiverName: null, // 收货人姓名 receiverMobile: null, // 收货人手机号 orderDateFrom: null, // 订单开始日期 orderDateEnd: null, // 订单结束日期 originalOrderCode: null, // 交易订单号 warehouseId: null, // 仓库id deliveryType: null, // 提货方式 outStorageOrderCode: null, // 出库单号 searchText: '', orderDateFromDate: null, orderDateEndDate: null, isHighlightFilter: false, }), deliveryCode: null, // 提货码 }; } componentWillMount() { InteractionManager.runAfterInteractions(() => this.onRefresh()) } componentDidMount() { } componentWillUnmount() { } //渲染 render() { return ( <PrimaryHeader title={'订单'} showBackAction={false} navigation={this.props.navigation}> {this.renderTab()} {this.renderSearchBar()} {this.renderListView()} </PrimaryHeader> ); } renderLoading = () => { // render 加载菊花 return ( <View style={{ width: '100%', height: '100%', position: 'absolute', justifyContent: 'center', alignItems: 'center' }}> <ActivityIndicator /> </View> ) } renderSearchBar = () => { // render 搜索 筛选 return ( <View style={{ backgroundColor: 'white' }}> <CommonSearchBar cancelBtnStyle={this.state.searchParams[this.state.selectTab].isHighlightFilter && { color: Constant.colorPrimary }} text={this.state.searchParams[this.state.selectTab].searchText} placeholder={'收货人姓名/手机号'} placeholderTextColor={Constant.colorTxtAlert} onChange={(text) => { this.setSearchParams({ searchText: text }) }} onSearch={(text) => { // 点击收索将筛选页面的searchParams的参数置为null this.setSearchParams({ receiverName: null, // 收货人姓名 receiverMobile: null, // 收货人手机号 orderDateFrom: null, // 订单开始日期 orderDateEnd: null, // 订单结束日期 originalOrderCode: null, // 交易订单号 warehouseId: null, // 仓库id deliveryType: null, // 提货方式 outStorageOrderCode: null, // 出库单号 orderDateFromDate: null, orderDateEndDate: null, searchText: text, isHighlightFilter: false }, () => this.loadListData(false)) }} onFilter={() => this.navigate('OrderFilter', { // 跳转到筛选页面 orderCallback: this.orderCallback, type: this.state.selectTab, searchParams: this.state.searchParams[this.state.selectTab] })} isOnFocus={false} clear={() => this.setSearchParams({ searchText: '' }, () => { // 清空文本框,如果dataArray有值的话,并且不聚焦的时候,进行网络请求一次 if (!this.state.searchParams[this.state.selectTab].isHighlightFilter && this.state.listParams[this.state.selectTab].dataArray.length == 0) { this.onRefresh() } })} /> </View> ) } setSearchParams(obj = {}, callBack) { // 状态机对象中的字段重置 let newSearchParams = this.state.searchParams; newSearchParams[this.state.selectTab] = Object.assign({}, newSearchParams[this.state.selectTab], obj); this.setState({ searchParams: newSearchParams }, callBack && callBack()) } orderCallback = (data) => { // callback数据 if (data) { // 如果筛选页面参数字段有值的话,就将筛选二字默认高亮 if (data.receiverName || data.receiverMobile || data.orderDateFrom || data.orderDateEnd || data.originalOrderCode || data.warehouseId || data.deliveryType || data.outStorageOrderCode ) { data.isHighlightFilter = true; } else { data.isHighlightFilter = false; } this.setSearchParams(data, () => this.onRefresh()) } } renderListView = () => { // 渲染listView return ( <CommonListView dataSource={this.dataSource[this.state.selectTab]} renderRow={this.renderRow} onRefresh={this.onRefresh} onLoadMore={this.onLoadMore} listState={this.state.listParams[this.state.selectTab].listState} enableLoadMore={this.state.listParams[this.state.selectTab].enableLoadMore} style={{ flex: 1 }} > { <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: Constant.colorBackgroundDefault, }}> {/*<Image style={{width: Constant.scale(80), height: Constant.scale(80), resizeMode: 'contain'}} source={require('../img/order/ic_noData.png')} />*/} <Text style={{ fontSize: 16, color: Constant.colorTxtContent, marginTop: Constant.scale(25) }}>您还没有相关订单哦~</Text> </View> } </CommonListView> ) } renderRow = (rowData, sectionID, rowID) => { // renderRow return ( <OrderCommonCell rowData={rowData} itemClick={() => { this.navigate('OrderDetail', { data: rowData }) }} logisticsClick={(originalOrderCode) => { this.logisticsClick(originalOrderCode, rowData) }} pickupClick={() => this.pickupClick(rowData.originalOrderId, rowData)} outStockDetailClick={() => { this.goOutStockDetail(rowData) }} /> ) } goOutStockDetail = (rowData) => { let params = {} params.id = rowData.outStorageOrderId Api.outStockDetail(params).then((data) => { this.navigate('OutStockDetail', { data: data.data }) }).catch((err) => { }) } logisticsClick = (originalOrderCode, rowData) => { // 物流出库 Alert.alert( '物流出库', '云商订单号:' + originalOrderCode + '\n您确定该订单货品转出库吗?', [ { text: '否', }, { text: '是', onPress: () => this.logisticsOutStore(rowData) } ]); } logisticsOutStore = (rowData) => { // 确定物流出库 this.navigate('OutStock', { outStockData: rowData }); } pickupClick = (id, rowData) => { // 自提出库点击事件 Widget.Popup.show(<AlertCodeInput confirm={(code) => { Widget.Popup.hide(); InteractionManager.runAfterInteractions(() => { this.sureDeliveryGoods(code, id, rowData) }) }} cancel={() => Widget.Popup.hide()} />, { animationType: 'fade', backgroundColor: '#00000000', onMaskClose: () => { Widget.Popup.hide() } }) } sureDeliveryGoods = (code, id, rowData) => { // 提货码 确定按钮 Api.verifyPreprocessCode({ fetchCode: code, orderId: id }).then((result) => { this.navigate('OutStock', { outStockData: rowData, fetchCode: code }); }).catch((error) => { }); } renderTab() { // render 顶部tab return ( <ScrollableTabView onChangeTab={(obj) => { if (obj.i != this.state.selectTab) { // ********* 解决切换数据源的时候,单个listView导致数据源无法马上改变 ********* this.dataSource[obj.i] = this.dataSource[obj.i].cloneWithRows([]) // 先置空,然后再将数据源cloneWithRows, 因为我们本地状态机保存了dataArray数组 this.setState({ selectTab: obj.i }, () => { // 判断dataArray.length == 0 ,这样解决 切换数据源的时候,只保证数据为空的时候才下拉刷新 this.state.listParams[obj.i].dataArray.length == 0 && InteractionManager.runAfterInteractions(() => this.onRefresh()) this.dataSource[obj.i] = this.dataSource[obj.i].cloneWithRows(this.state.listParams[obj.i].dataArray) this.setState({}) }) } }} style={{ flex: 0, backgroundColor: Constant.colorBackgroundDefault, }} scrollWithoutAnimation={true} renderTabBar={() => { return ( <DefaultTabBar activeTextColor={Constant.colorTxtPrimary} inactiveTextColor='#777777' tabStyle={{ backgroundColor: '#FFFFFF', paddingTop: Constant.scale(8) }} underlineStyle={{ backgroundColor: Constant.colorTxtPrimary, height: 2 }} /> ) }}> <View style={{ height: 0 }} tabLabel='待出库' /> <View style={{ height: 0 }} tabLabel='已出库' /> </ScrollableTabView> ) } onRefresh = () => { // 下拉刷新 let newListParams = this.state.listParams; newListParams[this.state.selectTab] = Object.assign({}, newListParams[this.state.selectTab], { listState: CommonListView.STATE_REFRESH, }); this.setState({ listParams: newListParams }, () => { //TODO 下拉刷新 this.loadListData(false) }); }; onLoadMore = () => { // 上拉加载 let newListParams = this.state.listParams; newListParams[this.state.selectTab] = Object.assign({}, newListParams[this.state.selectTab], { listState: CommonListView.STATE_LOADING_MORE, }); this.setState({ listParams: newListParams }, () => { //TODO 加载更多 this.loadListData(true) }); }; loadListData = (loadMore) => { // 加载列表数据 const selectTab = this.state.selectTab let pageNum = 1; if (!loadMore) { } else { pageNum = this.state.listParams[selectTab].pageNum + 1; } let orderStatus = null; let deliveryType = 0; let order = 0; switch (selectTab) { case 0: orderStatus = '1,2,3'; // 待出库订单状态 order = 0; // 正序排列 break; case 1: orderStatus = '4'; // 已出库订单状态 order = 1; // 倒序排列 break; } let params = {} let searchParams = this.state.searchParams[selectTab] if (searchParams.searchText && searchParams.searchText !== '') { params.receiverNameOrMobile = searchParams.searchText } if (searchParams.receiverName) { params.receiverName = searchParams.receiverName } if (searchParams.receiverMobile) { params.receiverMobile = searchParams.receiverMobile } if (searchParams.orderDateFrom) { let orderDateFrom = DateUtil.formatDate(new Date(searchParams.orderDateFromDate).getTime(), 'yyyy-MM-dd 00:00') params.orderDateFrom = orderDateFrom } if (searchParams.orderDateEnd) { let orderDateEnd = DateUtil.formatDate(new Date(searchParams.orderDateEndDate).getTime(), 'yyyy-MM-dd 23:59') params.orderDateEnd = orderDateEnd } if (searchParams.originalOrderCode) { params.originalOrderCode = searchParams.originalOrderCode } if (searchParams.warehouseId) { params.warehouseId = searchParams.warehouseId } if (searchParams.deliveryType) { deliveryType = searchParams.deliveryType } if (searchParams.outStorageOrderCode) { params.outStorageOrderCode = searchParams.outStorageOrderCode } params.order = order; params.pageNum = pageNum params.orderStatus = orderStatus params.deliveryType = deliveryType Api.orderList(params).then((json) => { if (json && json.data && json.data.list) { let hasMore = json.data.pages > json.data.pageNum; let oldArray = this.state.listParams[selectTab].dataArray; let newArray = []; if (loadMore) { newArray = oldArray.concat(json.data.list) } else { newArray = json.data.list; } let newListParams = this.state.listParams; newListParams[selectTab] = Object.assign([], newListParams[selectTab]); newListParams[selectTab].pageNum = json.data.pageNum; newListParams[selectTab].dataArray = newArray; newListParams[selectTab].enableLoadMore = hasMore; newListParams[selectTab].listState = hasMore ? CommonListView.STATE_HAS_MORE : newArray.length == 0 ? CommonListView.STATE_INIT : CommonListView.STATE_NO_MORE; this.dataSource[selectTab] = this.dataSource[selectTab].cloneWithRows(newArray, null); this.setState({ listParams: newListParams, }) } else { // 后端接口没数据的时候,返回的字段为data={}空对象,将dataArray和数据源等置空 let newListParams = this.state.listParams; newListParams[selectTab] = Object.assign([], newListParams[selectTab]); newListParams[selectTab].enableLoadMore = false; newListParams[selectTab].dataArray = []; newListParams[selectTab].listState = CommonListView.STATE_INIT this.dataSource[selectTab] = this.dataSource[selectTab].cloneWithRows([]); this.setState({}) } }).catch((error) => { // 解决异常的时候,将加载菊花隐藏 let newListParams = this.state.listParams; newListParams[selectTab] = Object.assign([], newListParams[selectTab]); newListParams[selectTab].listState = CommonListView.STATE_INIT this.setState({ listParams: newListParams }) }) };};
阅读全文
0 0
- React Native 多个列表共用一个ListView
- React Native ListView列表多个数据源和状态机,取值,刷新状态机
- React-Native基础_5.列表视图ListView
- React Native 基础篇 之 ListView 产品列表实现
- 【React Native开发】- ListView垂直的滚动列表
- React-Native基础_5.列表视图ListView 网络数据展示
- react native用Listview从列表页跳到详情页
- react-native listView 分节
- React-Native 中的ListView
- React-native listview换行
- react-native 水平ListView
- React-Native ListView学习
- React-Native ListView
- React native ListView初识
- React-Native 之ListView
- react-native listview使用
- React Native 组件 ListView
- 初识react-native ListView
- 使用PHAsset获取图像或视频文件的大小
- 图解正向代理、反向代理、透明代理推荐
- 【腾讯TMQ】Android so的热升级尝试
- 【蓝桥杯】【神秘三位数】
- 万树IT:Android和java学哪个好?
- React Native 多个列表共用一个ListView
- 终端颜色
- FFMPEG 之视频解码
- AngularJs+Bootstrap Table $compile动态生成html
- java,this不能和super同时使用 并且放在第一行
- jvm工具看内存泄露
- Eclipse安装Gradle插件
- 安卓剪裁图片(直接操作bitmap)
- 重磅消息!微信或为确保用户账户安全或关停这一功能…