UNPKG

uatcomponent

Version:
110 lines (105 loc) 3.02 kB
/** * 备注: * create by Mark at 2019-July */ import React, { Component } from 'react'; import { View, Text, Image, TouchableOpacity, StyleSheet, ViewStyle, Dimensions, } from 'react-native'; import { ResponseClass,URequestModel,RecommentCategoryModel,ComponentProps,RecommendCategoryCallbackParams, RecommendItem, LinkType } from "../../model"; import { CategoryItem } from 'uatcomponent/src/container/recommendCategory/view/categoryItem'; import { autoBaseUrl } from 'uatcomponent/src/util'; type Props = { style : ViewStyle, } & ComponentProps<RecommentCategoryModel,RecommendCategoryCallbackParams>; type State = { isLoading : Boolean, data : RecommendItem[], hasError : Boolean, }; const SCREEN_WIDTH : Number = Dimensions.get('window').width; export class RecommendCategory extends Component <Props,State>{ static defaultProps :Props = { } state:State={ isLoading : true, data : [], hasError : false, } /**获取数据 */ getData = ()=>{ let requestInfo : URequestModel = this.props.request(this.props.data); if(!requestInfo)return ; let opt : Object = {method:requestInfo.method, headers:requestInfo.header}; if(requestInfo.method!='GET'){ opt.body = JSON.stringify(requestInfo.params); } fetch(requestInfo.url,opt) .then(res=>res.json()) .then(res=>{ this.handleForComplete(); let resp : ResponseClass = new ResponseClass(res); this.handleForResponse(resp); }) .catch(err=>{ this.handleForComplete(); this.handleForFail() }) } componentDidMount(){ this.getData(); } /**处理请求完成时的基本操作 */ handleForComplete = ()=>{ this.setState({isLoading:false,hasError:false}); } /**处理响应数据 */ handleForResponse = (res:ResponseClass<RecommendItem[]>)=>{ if(res.isSuccess()){ this.setState({data:res.data.map(item=>new RecommendItem(item))}); }else{ this.handleForFail() } } /**处理异常事件 */ handleForFail = ()=>{ this.setState({hasError:true}) } /**渲染异常时候的内容 */ errorRender = ()=>{ return ( <View> <Text>获取分类异常,点击重试</Text> </View> ) } render(){ const {style,data,baseUrl,} = this.props; const width : Number = SCREEN_WIDTH / data.content.linesize ; const list : RecommendItem[] = this.state.data; const {hasError,isLoading} = this.state; if(hasError)return this.errorRender() return ( <View style={[styles.container,style]}> { list.map(item=><CategoryItem style={{width:width}} data={{...item,_pic:autoBaseUrl(baseUrl,item._pic)}} onClick={(d)=>{this.props.onClick && this.props.onClick(data,{ linkType : LinkType.ProductCategory, link : `category?categoryId=${d.item_id}`, title : d.title, pic : d.pic, })}}/>) } </View> ) } } const styles = StyleSheet.create({ container:{flexDirection:'row',flexWrap:'wrap'}, })