1.数据持久化

数据持久化是移动端的一个重要部分,刚发现 Realm 原来已经支持 React-Native 了

步骤一: 引入 realm

$ npm install realm --save

步骤二: 添加 Realm 与 工程的链接

react-native >= 0.31.0

react-native link realm

react-native  <  0.31.0

rnpm link realm

首先,在为了方便使用,也为了减少第三方框架对工程的 “污染”,我们需要对框架进行一次 基础 的封装。

realmStorage.js

/*** 数据持久化* 本地数据存储*/
// 提供变量,便于外部调用
var RealmBase = {};import Realm from 'realm';// 创建数据表(首页)
const HomeSchame = {name:'HomeData',properties:{id:'int',title:'string',image:'string',mall:'string', // 商城平台pubtime:'string',fromsite:'string',}
};// 创建数据表(海淘)
const HTSchame = {name:'HTData',properties:{id:'int',title:'string',image:'string',mall:'string',pubtime:'string',fromsite:'string',}
};// 初始化realm
let realm = new Realm({schema:[HomeSchame, HTSchame]});// 增加
RealmBase.create = function (schame, data) {realm.write(() => {for (let i = 0; i<data.length; i++) {let temp = data[i];realm.create(schame, {id:temp.id, title:temp.title, image:temp.image, mall:temp.mall, pubtime:temp.pubtime, fromsite:temp.fromsite});}})
}// 查询全部数据
RealmBase.loadAll = function (schame) {return realm.objects(schame);
}// 条件查询
RealmBase.filtered = function (schame, filtered) {// 获取对象let objects = realm.objects(schame);// 筛选let object = objects.filtered(filtered);if (object) {   // 有对象return object;}else {return '未找到数据';}
}// 删除所有数据
RealmBase.removeAllData = function (schame) {realm.write(() => {// 获取对象let objects = realm.objects(schame);// 删除表realm.delete(objects);})
}global.RealmBase = RealmBase;

GDMain.js 调用

// 引入 HTTP封装组件
import HTTP from '../http/HTTPBase';// 引入 本地数据存储封装组件 (数据持久化)
import RealmStorage from '../storage/realmStorage';

GDHome.js

/*** 首页*/
import React, { Component } from 'react';
import {StyleSheet,Text,View,TouchableOpacity,Image,ListView,Dimensions,ActivityIndicator,Modal, // 模态AsyncStorage, // 缓存数据库(数据持久化)
} 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';
// 引入 近半小时热门组件
import HalfHourHot from './GDHalfHourHot';
// 引入 搜索页面组件
import Search from '../main/GDSearch';
// 引入 cell
import CommunalHotCell from '../main/GDCommunalHotCell';
// 引入 详情页 组件
import CommunalDetail from '../main/GDCommunalDetail';
// 引入 空白页组件
import NoDataView from '../main/GDNoDataView';export default class GDHome extends Component {// 构造constructor(props) {super(props);// 初始状态this.state = {dataSource: new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}), // 数据源 优化loaded: false, // 用于判断是否显示空白页isModal: 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);}// 存储数组中最后一个元素的idlet cnlastID = responseData.data[responseData.data.length - 1].id;AsyncStorage.setItem('cnlastID', cnlastID.toString());  // 只能存储字符或字符串// 首页存储数组中第一个元素的idlet 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,});// 存储数组中最后一个元素的idlet cnlastID = responseData.data[responseData.data.length - 1].id;AsyncStorage.setItem('cnlastID', cnlastID.toString());  // 只能存储字符或字符串}).catch((error) => {})}// 加载更多数据操作loadMore() {// 读取存储的idAsyncStorage.getItem('cnlastID').then((value) => {// 数据加载操作this.loadMoreData(value);})}// 模态到近半小时热门pushToHalfHourHot() {this.setState({isModal: true})}// 跳转到搜索页面pushToSearch() {this.props.navigator.push({component: Search,})}// 安卓模态销毁模态onRequestClose() {this.setState({isModal: false})}// 关闭模态closeModal(data) {this.setState({isModal:data})}// 返回左边按钮renderLeftItem() {// 将组件返回出去return(<TouchableOpacityonPress={() => {this.pushToHalfHourHot()}}><Image source={{uri:'hot_icon_20x20'}} style={styles.navbarLeftItemStyle} /></TouchableOpacity>);}// 返回中间按钮renderTitleItem() {return(<TouchableOpacity><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>);}// 根据网络状态决定是否渲染 listViewrenderListView() {if(this.state.loaded === false) {// 显示空白页return(<NoDataView />);}else{return(<PullList   // 将ListView 改为 PullList// 下拉刷新onPullRelease={(resolve) => this.loadData(resolve)}// 数据源 通过判断dataSource是否有变化,来判断是否要重新渲染dataSource={this.state.dataSource} renderRow={this.renderRow.bind(this)}// 隐藏水平线showsHorizontalScrollIndicator={false}style={styles.listViewStyle}initialListSize={5}// 返回 listView 头部renderHeader={this.renderHeader}// 上拉加载更多onEndReached={this.loadMore}onEndReachedThreshold={60}renderFooter={this.renderFooter}/>);}}// 通过id 跳转详情页pushToDetail(value) {this.props.navigator.push({component:CommunalDetail,params: {url: 'https://guangdiu.com/api/showdetail.php' + '?' + 'id=' + value}})}// 返回每一行cell的样式renderRow(rowData) {// 使用cell组件return(<TouchableOpacity// 给每一个cell添加点击事件onPress={() => this.pushToDetail(rowData.id)}><CommunalHotCellimage={rowData.image}title={rowData.title}/></TouchableOpacity>);}// 生命周期 组件渲染完成 已经出现在dom文档里componentDidMount() {// 请求数据this.loadData();}render() {return (<View style={styles.container}>{/* 初始化模态 */}<ModalanimationType='slide'  // 动画 底部弹窗transparent={false}  // 透明度visible={this.state.isModal}  // 可见性onRequestClose={() => this.onRequestClose()}  // 销毁><NavigatorinitialRoute={{name:'halfHourHot',component:HalfHourHot}}renderScene={(route, navigator) => {let Component = route.component;return <ComponentremoveModal={(data) => this.closeModal(data)}{...route.params}navigator={navigator} />}} /></Modal>{/* 导航栏样式 */}<CommunalNavBarleftItem = {() => this.renderLeftItem()}titleItem = {() => this.renderTitleItem()}rightItem = {() => this.renderRightItem()}/>{/* 根据网络状态决定是否渲染 listView */}{this.renderListView()}</View>);}
}const styles = StyleSheet.create({container: {flex: 1,alignItems: 'center',},navbarLeftItemStyle: {width:20,height:20,marginLeft:15,},navbarTitleItemStyle: {width:66,height:20,},navbarRightItemStyle: {width:20,height:20,marginRight:15,},listViewStyle: {width:width,},
});

核心代码:

// 加载最新数据网络请求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);}// 存储数组中最后一个元素的idlet cnlastID = responseData.data[responseData.data.length - 1].id;AsyncStorage.setItem('cnlastID', cnlastID.toString());  // 只能存储字符或字符串// 首页存储数组中第一个元素的idlet 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,});})}

2.因为 realm 下载的内容过大,不易上传至 github 需要在 .gitignore 上设置 忽略

/node_modules/realm/*

3.设置 ListView 默认显示条数,避免列表下出现空白

4.自定义详情cell

首先,还是一样,我们先来创建 GDCommunalCell 文件,并且我们将前面 自定义cell 里面的内容 copy 一下,放到这个文件中,并进行相应修改:

GDCommunalCell.js

/*** 公共 Cell*/
import React, { Component, PropTypes } from 'react';
import {StyleSheet,Text,View,Dimensions,Platform,Image,
} from 'react-native';// 获取屏幕宽高
const {width, height} = Dimensions.get('window');export default class GDCommunalCell extends Component {// 定义成员属性static propTypes = {image:PropTypes.string,title:PropTypes.string,mall:PropTypes.string, // 平台pubTime:PropTypes.string, // 时间fromSite:PropTypes.string, // 来源};renderDate(pubTime, fromSite) {// 时间差的计算let minute = 1000 * 60;     // 1分钟let hour = minute * 60;     // 1小时let day = hour * 24;        // 1天let week = day * 7;         // 1周let month = day * 30;       // 1个月// 计算时间差let now = new Date().getTime();     // 获取当前时间let diffValue = now - Date.parse(pubTime.replace(/-/gi, "/"));if (diffValue < 0) return;let monthC = diffValue/month;   // 相差了几个月let weekC = diffValue/week;     // 相差几周let dayC = diffValue/day;       // 相差几天let hourC = diffValue/hour      // 相差几小时let minuteC = diffValue/minute; // 相差几分钟let result;if (monthC >= 1) {result = parseInt(monthC) + "月前";}else if (weekC >= 1) {result = parseInt(weekC) + "周前";}else if (dayC >= 1) {result = parseInt(dayC) + "天前";}else if (hourC >= 1) {result = parseInt(hourC) + "小时前";}else if (minuteC >= 1) {result = parseInt(minuteC) + "分钟前";}else result = "刚刚";return result + ' · ' + fromSite;}render() {return (<View style={styles.container}>{/* 左边图片 */}<Image source={{uri:this.props.image === '' ? 'defaullt_thumb_83x83' : this.props.image}} style={styles.imageStyle} />{/* 中间 */}<View style={styles.centerViewStyle}>{/* 标题 */}<View><Text numberOfLines={3} style={styles.titleStyle}>{this.props.title}</Text></View>{/* 详情 */}<View style={styles.detailViewStyle}>{/* 平台 */}<Text style={styles.detailMallStyle}>{this.props.mall}</Text>{/* 时间 + 来源 */}<Text style={styles.timeStyle}>{this.renderDate(this.props.pubTime, this.props.fromSite)}</Text></View></View>{/* 右边的箭头 */}<Image source={{uri:'icon_cell_rightArrow'}} style={styles.arrowStyle} /></View>);}
}const styles = StyleSheet.create({container: {flexDirection:'row',alignItems:'center',justifyContent:'space-between',backgroundColor:'white',height:100,width:width,borderBottomWidth:0.5,borderBottomColor:'gray',marginLeft:15},imageStyle: {width:70,height:70,},centerViewStyle: {height:70,justifyContent:'space-around',},titleStyle: {width:width * 0.65,},detailViewStyle: {flexDirection:'row',justifyContent:'space-between',alignItems:'center'},detailMallStyle: {fontSize:12,color:'green',},timeStyle: {fontSize:12,color:'gray',},arrowStyle: {width:10,height:10,marginRight:30,}
});

GDHome.js  及 GDHt.js 调用

// 引入 公共cell
import CommunalCell from '../main/GDCommunalCell';

GDHome.js

/*** 首页*/
import React, { Component } from 'react';
import {StyleSheet,Text,View,TouchableOpacity,Image,ListView,Dimensions,ActivityIndicator,Modal, // 模态AsyncStorage, // 缓存数据库(数据持久化)
} 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';
// 引入 近半小时热门组件
import HalfHourHot from './GDHalfHourHot';
// 引入 搜索页面组件
import Search from '../main/GDSearch';
// 引入 公共cell
import CommunalCell from '../main/GDCommunalCell';
// 引入 详情页 组件
import CommunalDetail from '../main/GDCommunalDetail';
// 引入 空白页组件
import NoDataView from '../main/GDNoDataView';export default class GDHome extends Component {// 构造constructor(props) {super(props);// 初始状态this.state = {dataSource: new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}), // 数据源 优化loaded: false, // 用于判断是否显示空白页isModal: 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);}// 存储数组中最后一个元素的idlet cnlastID = responseData.data[responseData.data.length - 1].id;AsyncStorage.setItem('cnlastID', cnlastID.toString());  // 只能存储字符或字符串// 首页存储数组中第一个元素的idlet 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,});// 存储数组中最后一个元素的idlet cnlastID = responseData.data[responseData.data.length - 1].id;AsyncStorage.setItem('cnlastID', cnlastID.toString());  // 只能存储字符或字符串}).catch((error) => {})}// 加载更多数据操作loadMore() {// 读取存储的idAsyncStorage.getItem('cnlastID').then((value) => {// 数据加载操作this.loadMoreData(value);})}// 模态到近半小时热门pushToHalfHourHot() {this.setState({isModal: true})}// 跳转到搜索页面pushToSearch() {this.props.navigator.push({component: Search,})}// 安卓模态销毁模态onRequestClose() {this.setState({isModal: false})}// 关闭模态closeModal(data) {this.setState({isModal:data})}// 返回左边按钮renderLeftItem() {// 将组件返回出去return(<TouchableOpacityonPress={() => {this.pushToHalfHourHot()}}><Image source={{uri:'hot_icon_20x20'}} style={styles.navbarLeftItemStyle} /></TouchableOpacity>);}// 返回中间按钮renderTitleItem() {return(<TouchableOpacity><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>);}// 根据网络状态决定是否渲染 listViewrenderListView() {if(this.state.loaded === false) {// 显示空白页return(<NoDataView />);}else{return(<PullList   // 将ListView 改为 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}/>);}}// 通过id 跳转详情页pushToDetail(value) {this.props.navigator.push({component:CommunalDetail,params: {url: 'https://guangdiu.com/api/showdetail.php' + '?' + 'id=' + value}})}// 返回每一行cell的样式renderRow(rowData) {// 使用cell组件return(<TouchableOpacity// 给每一个cell添加点击事件onPress={() => this.pushToDetail(rowData.id)}><CommunalCellimage={rowData.image}title={rowData.title}mall={rowData.mall}  // 平台pubTime={rowData.pubtime}  // 时间fromSite={rowData.fromsite}  // 来源/></TouchableOpacity>);}// 生命周期 组件渲染完成 已经出现在dom文档里componentDidMount() {// 请求数据this.loadData();}render() {return (<View style={styles.container}>{/* 初始化模态 */}<ModalanimationType='slide'  // 动画 底部弹窗transparent={false}  // 透明度visible={this.state.isModal}  // 可见性onRequestClose={() => this.onRequestClose()}  // 销毁><NavigatorinitialRoute={{name:'halfHourHot',component:HalfHourHot}}renderScene={(route, navigator) => {let Component = route.component;return <ComponentremoveModal={(data) => this.closeModal(data)}{...route.params}navigator={navigator} />}} /></Modal>{/* 导航栏样式 */}<CommunalNavBarleftItem = {() => this.renderLeftItem()}titleItem = {() => this.renderTitleItem()}rightItem = {() => this.renderRightItem()}/>{/* 根据网络状态决定是否渲染 listView */}{this.renderListView()}</View>);}
}const styles = StyleSheet.create({container: {flex: 1,alignItems: 'center',},navbarLeftItemStyle: {width:20,height:20,marginLeft:15,},navbarTitleItemStyle: {width:66,height:20,},navbarRightItemStyle: {width:20,height:20,marginRight:15,},listViewStyle: {width:width,},
});

GDHt.js

/*** 海淘折扣*/
import React, { Component } from 'react';
import {StyleSheet,Text,View,TouchableOpacity,Image,ListView,Dimensions,ActivityIndicator,Modal, // 模态AsyncStorage, // 缓存数据库(数据持久化)
} 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';
// 引入 近半小时热门组件
import USHalfHourHot from './GDUSHalfHourHot';
// 引入 搜索页面组件
import Search from '../main/GDSearch';
// 引入 cell
import CommunalCell from '../main/GDCommunalCell';
// 引入 详情页 组件
import CommunalDetail from '../main/GDCommunalDetail';
// 引入 空白页组件
import NoDataView from '../main/GDNoDataView';export default class GDHome extends Component {// 构造constructor(props) {super(props);// 初始状态this.state = {dataSource: new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}), // 数据源 优化loaded: false, // 用于判断是否显示空白页isModal: 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);}// 存储数组中最后一个元素的idlet uslastID = responseData.data[responseData.data.length - 1].id;AsyncStorage.setItem('uslastID', uslastID.toString());  // 只能存储字符或字符串// 首页存储数组中第一个元素的idlet 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,});// 存储数组中最后一个元素的idlet uslastID = responseData.data[responseData.data.length - 1].id;AsyncStorage.setItem('uslastID', uslastID.toString());  // 只能存储字符或字符串}).catch((error) => {})}// 加载更多数据操作loadMore() {// 读取存储的idAsyncStorage.getItem('uslastID').then((value) => {// 数据加载操作this.loadMoreData(value);})}// 模态到近半小时热门pushToHalfHourHot() {this.setState({isModal: true})}// 跳转到搜索页面pushToSearch() {this.props.navigator.push({component: Search,})}// 安卓模态销毁模态onRequestClose() {this.setState({isModal: false})}// 关闭模态closeModal(data) {this.setState({isModal:data})}// 返回左边按钮renderLeftItem() {// 将组件返回出去return(<TouchableOpacityonPress={() => {this.pushToHalfHourHot()}}><Image source={{uri:'hot_icon_20x20'}} style={styles.navbarLeftItemStyle} /></TouchableOpacity>);}// 返回中间按钮renderTitleItem() {return(<TouchableOpacity><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>);}// 根据网络状态决定是否渲染 listViewrenderListView() {if(this.state.loaded === false) {// 显示空白页return(<NoDataView />);}else{return(<PullList   // 将ListView 改为 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}/>);}}// 通过id 跳转详情页pushToDetail(value) {this.props.navigator.push({component:CommunalDetail,params: {url: 'https://guangdiu.com/api/showdetail.php' + '?' + 'id=' + value}})}// 返回每一行cell的样式renderRow(rowData) {// 使用cell组件return(<TouchableOpacity// 给每一个cell添加点击事件onPress={() => this.pushToDetail(rowData.id)}><CommunalCellimage={rowData.image}title={rowData.title}mall={rowData.mall}  // 平台pubTime={rowData.pubtime}  // 时间fromSite={rowData.fromsite}  // 来源/></TouchableOpacity>);}// 生命周期 组件渲染完成 已经出现在dom文档里componentDidMount() {// 请求数据this.loadData();}render() {return (<View style={styles.container}>{/* 初始化模态 */}<ModalanimationType='slide'  // 动画 底部弹窗transparent={false}  // 透明度visible={this.state.isModal}  // 可见性onRequestClose={() => this.onRequestClose()}  // 销毁><NavigatorinitialRoute={{name:'halfHourHot',component:USHalfHourHot}}renderScene={(route, navigator) => {let Component = route.component;return <ComponentremoveModal={(data) => this.closeModal(data)}{...route.params}navigator={navigator} />}} /></Modal>{/* 导航栏样式 */}<CommunalNavBarleftItem = {() => this.renderLeftItem()}titleItem = {() => this.renderTitleItem()}rightItem = {() => this.renderRightItem()}/>{/* 根据网络状态决定是否渲染 listView */}{this.renderListView()}</View>);}
}const styles = StyleSheet.create({container: {flex: 1,alignItems: 'center',},navbarLeftItemStyle: {width:20,height:20,marginLeft:15,},navbarTitleItemStyle: {width:66,height:20,},navbarRightItemStyle: {width:20,height:20,marginRight:15,},listViewStyle: {width:width,},
});

  

.

React-Native 之 GD (十三)数据持久化(realm) 及 公共Cell相关推荐

  1. android realm 分页,iOS Realm数据持久化--Realm基础知识 (一)

    目录 1.Realm简介 Realm是新兴的跨平台数据库解决方案,提供多语言支持(JAVA.Objective-C.Swift.JS..Net),你可以轻松的在iOS.Android等移动平台接入.R ...

  2. React Native专题

    未经授权不得转载: 出处地址:http://www.lcode.org 本文出自:[江清清的技术专栏] 本React Native讲解专题:主要讲解了React Native开发,由基础环境搭建配置入 ...

  3. React Native专题-江清清

    本React Native讲解专题:主要讲解了React Native开发,由基础环境搭建配置入门,基础,进阶相关讲解. 刚创建的React Native交流8群:533435865  欢迎各位大牛, ...

  4. React Native专题-江

    (一).基本介绍: 江博客http://blog.csdn.net/jiangqq781931404/article/category/6055594 React Native For Android ...

  5. React Native开发(一)

    本React Native讲解专题:主要讲解了React Native开发,由基础环境搭建配置入门,基础,进阶相关讲解. 关于React Native各种疑难杂症,问题深坑总结方案请点击查看: Mac ...

  6. React Native应用实现步骤

    React Native应用实现步骤 在整个应用设计中,始终按照自下而上的原则进行.在大型的项目中,自下而上的设计方式简单,可以并行工作,并且可以在构建的同时写测试用例. React Native设计 ...

  7. iOS新知识学习之React Native开发工具集

    本文整理了React Native iOS开发过程中有用的工具.服务.测试.库以及网站等. 工具 你可以选择不同的开发环境:DECO.EXPO或者你可以使用Nuclide+Atom,目前我使用EXPO ...

  8. 从零学React Native之13 持久化存储

    数据持久化就是指应用程序将某些数据存储在手机存储空间中. 借助native存储 这种方式不言而喻,就是把内容传递给native层,通过原生API存储,详见从零学React Native之05混合开发 ...

  9. 【REACT NATIVE 系列教程之十三】利用LISTVIEW与TEXTINPUT制作聊天/对话框获取组件实例常用的两种方式...

    本站文章均为 李华明Himi 原创,转载务必在明显处注明:  转载自[黑米GameDev街区] 原文链接: http://www.himigame.com/react-native/2346.html ...

最新文章

  1. 高文院士:中国在AI领域有哪些长板和短板
  2. lisp封装成vla函数_Lisp List 和函数式编程 (in Python)
  3. JAVA设计模式--单例模式
  4. 调度场算法与逆波兰表达式
  5. 如何破解您忘记的Windows密码
  6. python画图库matplotlib:初识
  7. 赵娜计算机,新学期 新起点 新征程——计算机学院2016级召开系列年级工作会议...
  8. Unity shader实现水效果(折射,反射,波浪,1.菲尼尔,深度颜色)
  9. pulse 去马赛克软件_打马赛克就安全了吗?AI消除马赛克,上线三天收获近7000星...
  10. 项目服务接口设计_Spring Boot Security 整合 OAuth2 设计安全API接口服务
  11. java项目 服务器部署Word转成PDF乱码
  12. ffmpeg系列之两种视频解码方式
  13. matlab与或非语句,Matlab与或非等逻辑运算符使用教程分享
  14. Linux系统查看设备温度,技巧分享 Linux下查看cpu温度
  15. 爆火的羊了个羊背后暗含的广告变现逻辑是什么?
  16. Learn Go with tests 学习笔记(9)——Mocking
  17. 币种对应的转换因子(处理日元台币…
  18. arma找不到合适的模型_ARMA模型建模与预测指导
  19. Python字符串格式化占位操作解析
  20. 计算机中rom,计算机中rom指的是内存还是外存

热门文章

  1. 用treeview遍历文件夹(vb)
  2. 如果有什么想不开或者放不下的话,看看这里吧!(摘于网络)
  3. 63万张!旷视发布最大物体检测数据集Objects365,物体检测竞赛登陆CVPR
  4. 十个优衣库仓库理货员,只有一个能留下,机器已经上岗了
  5. 中国团队屠榜:COCOMapillary挑战赛包揽全部冠军
  6. 3个问题,1套非技术人员的AI方法论 | 哈佛商业评论最新热文
  7. 阿里巴巴的AI革命 | 4天云栖大会干货总结
  8. Docker (一、dockerfile-node.js)
  9. Python开发技术详解PDF
  10. linux 命令之 ps