function ViewMore({ hasMore, request, cursor, list }) { function handleOnAppear() { if (!hasMore) { return; } request(cursor); } return ( <View className="view-more" onAppear={handleOnAppear}> {hasMore ? ( <View className="view-more-tip">下拉获取更多</View> ) : list.length ? ( <View className="view-more-tip"> <View className="view-more-line"></View> 没有更多了 <View className="view-more-line"></View> </View> ) : ( <View /> )} </View> ); } const DefaultEmptyComponent = (props) => <View className="page-content-empty"></View>; //兜底展示
interface IProps { fetchData: any; params: any; [key: string]: any; } const defaultParams = { pageSize: 10, }; function WithPageList(PageItem, EmptyComponent = DefaultEmptyComponent) { return class HOC extends Component<IProps> { state = { list: [], loading: true, cursor: 1, hasMore: true, } componentDidMount() { const { cursor } = this.state; this.fetchData(cursor); } render() { const { list, hasMore, cursor } = this.state; const { fetchData, params, ...leftProps } = this.props; if (!list || !list.length) { return ( <View className="page-content"> <EmptyComponent /> </View> ); } return ( <View className="page-content"> <View className="page-list"> {list.map((item, index) => ( <PageItem key={index} data={item} {...leftProps} /> ))} </View> {list.length > 0 &&(<ViewMore hasMore={hasMore} cursor={cursor} request={this.fetchData} list={list} />)} </View> ); } fetchData = async (cursor) => { const { fetchData, params } = this.props; const { list } = this.state; try { const data = await fetchData({ ...defaultParams, ...params, currentPage: cursor, }); this.setState({ loading: false, hasMore: data.hasMore, list: [...list, ...data.list], cursor: cursor + 1, }); } catch (err) { this.setState({ loading: false, hasMore: false, }); } } } } export default WithPageList;
调用部分:
const List = WithPageList(<View
fetchData={RecordService.getPKList}//调用的接口 params={params}//传入的参数
>这里写循环组件的东西</View>); //调用