上拉加载更多及下拉刷新(Flatlist、SectionList)

思路

  • sectionList及FlatList都有属性refreshControl、onEndReachedThreshold(距离底部还有多远触发加载更多)、onEndReached(加载更多加载事件)
  • 传递参数loadType区分加载事件,loadType为refresh下拉刷新事件,loadType为more加载更多事件
  • 传递参数page,page为1下拉刷新事件,this.state.page += 1
    为加载更多事件
  • react-redux框架:在reducer中发起网络请求,添加状态onRefresh,
    onRefresh根据传过来的参数loadType判断:onRefresh: loadType === refresh 下拉刷新状态,为true,onMore: loadType === more 加载更多状态,为true,
  • 收到数据: onRefresh 为false, onMore为false, 添加状态hasMore, hasMore: 接收到的数据的长度/pageSize === 传过来的page,为true 还有更多数据,为false没有更多数据了

代码

前端js界面

_onMore = () => {
        // 有更多数据且不是正在加载更多状态下,请求更多数据
        if (this.props.message.hasMore && !this.props.message.onMore) {
            const {action, navigation, message} = this.props;

            this.state.page = this.state.page + 1;
            this.state.loadType = PageConstant.more;

            let params = {
                page: this.state.page,
                loadType: this.state.loadType,
            };
            action.requestMyMessages(navigation, message.messageArray, params, this._onLoad);
        }
    };

_onRefresh = () => {
        if (!this.props.message.onRefresh) {
            const {action, navigation} = this.props;
            this.state.page = 1;
            this.state.loadType = PageConstant.refresh;

            let params = {
                page: 1,
                loadType: this.state.loadType,
            };
            action.requestMyMessages(navigation, [], params, this._onLoad)
        }
    };

reducer

case types.my.requestMyMessages:
          return {
              ...state,
              navigation: action.navigation,
              params: action.params,
              array: action.array,
              onRefresh: action.params.loadType === PageConstant.refresh,
              onMore: action.params.loadType === PageConstant.more,
              callback: action.callback,
          };
      case types.my.receiveMyMessages:
          return {
              ...state,
              onRefresh: false,
              onMore: false,
              hasMore: action.messageArray.length / PageConstant.pageSize === state.params.page,
              messageArray: action.messageArray,
              onSubmit: false,
          };

你可能感兴趣的:(上拉加载更多及下拉刷新(Flatlist、SectionList))