2021-02-27 Taro 中加载更多的实现

大家好,我是本泽锅,去年公司选型,选中了Taro作为实现一码多端的框架!既然公司选中了就要开始学习了,正好分享下我在项目中使用的加载更多,并做了一点点封装。
首先要说明的是 Taro项目是基于react开发的,使用vue开发的小伙伴不知道有没有参考价值。
要实现加载更多 就要用到 Taro 提供的组件 ScrollView

<ScrollView
              scrollY={true}
              className={'pyq-tab-wrap page-wrap'}
              style={{height:scrollHeight+'px'}}
              onScrollToLower={this.loadData}
            >
            </ScrollView>

我们看看其中的一些需要用到的api
scrollY : 允许纵向滚动。
onScrollToLower:滚动到底部,会触发 scrolltolower 事件,这个事件就是加载更多的核心。
style: 其中涉及到 ScrollView 高度的动态计算,注意了这个高度要计算准确。

计算 ScrollView的高度

首先在state中设置一个默认值,然后在生命周期中componentWillMount 动态的计算出ScrollView的高度 windowHeight 是Taro提供的api可以算出当前屏幕的高度,rect是我当前tab的高度,减去之后就是ScrollView的高度,如图
WeChateabc76ead6999da00bf3ad8b93ae9334.png
this.state = {   
      scrollHeight:44,
    }

componentWillMount() {
  let rect = await getCompRectByClassName('.at-tabs__header')
      if(!!rect){
        const info = Taro.getSystemInfoSync()
        const { windowHeight } = info
        this.setState({scrollHeight:windowHeight - rect.height})
      }
  }

处理加载更多,首先定义两个值loading:正在加载中,hasMore:是否有加载更多
在生命周期函数componentDidMount 调用this.loadData 发起网络请求,这里将this.loadData和ScrollView提供的滚动到底部,会触发 scrolltolower 事件的api 结合起来。

this.state = {   
     loading: false,
     hasMore: true,
    pageNum:1,
    pageSize:15,
    teamList: [],
    }

componentDidMount(){
    this.loadData()
  }
loadData=()=>{
    const {loading,hasMore,pageNum,pageSize,teamList} = this.state
    if (!hasMore || loading) {
      return
    }
 this.setState({
        loading :true
      })
//此处是网络请求
getList = async (payload = {}) => {
    const res = await Serv.getList(payload);
    runInAction(() => {
     this.setState({
        loading : false
      })
      if(res.data.length<15){
         this.setState({
        hasMore :true
      })
      }
      let newList = this.state.teamList.concat(res.data)
      this.state.teamList = newList
      this.state.pageNum ++
    })
  }
  }

<ScrollView scrollY
                      className={'list_wrap'}
                      onScrollToLower={this.loadData}
                      style={{ height: getWindowHeight() }}>
            {loading &&
            <View className='home__loading'>
              <Text className='home__loading-txt'>正在加载中...</Text>
            </View>
            }
            {!hasMore &&
            <View className='home__loading home__loading--not-more'>
              <Text className='home__loading-txt'>没有更多了</Text>
            </View>
            }
          </ScrollView>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容