小编典典

从React js中的第一个API调用加载所有内容(延迟加载)后,进行第2个API调用

reactjs

我有一些.json文件。我需要将浏览器中第一个.json文件中的所有数据显示为延迟加载。当所有内容都从第一个.json文件加载
时(当用户scoll到页面末尾时), 我需要对第二个.json进行API调用 。我不应该一次进行所有API调用。如何使用react
js做到这一点。


阅读 310

收藏
2020-07-22

共1个答案

小编典典

利用javascript scrolleventListener并计算窗口滚动高度,以触发异步调用。

请在构造函数中绑定必要的方法并定义状态。这是代码

componentDidMount(){
  if(this.state.newData.length === 0){
    window.addEventListener('scroll', this.handleOnScroll);
    this.doQuery(1).then(res=>
      this.setState({
       newData: this.state.newData.slice().concat(res),
      requestSent: false
    }))
  }
}

componentWillUnmount() {
  window.removeEventListener('scroll', this.handleOnScroll);
}

handleOnScroll(){
  var scrollTop = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
  var scrollHeight = (document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight;
  var clientHeight = document.documentElement.clientHeight || window.innerHeight;
  var scrolledToBottom = Math.ceil(scrollTop + clientHeight) >= scrollHeight;
  if (scrolledToBottom) {
    this.setState({
      scrollCounter: this.state.scrollCounter + Math.floor(scrolledToBottom)
    },()=>{
            if(this.state.scrollCounter<4){
      this.doQuery(this.state.scrollCounter).then(res=>
      (res===BUSY)
        ? false
        : this.setState({
            newData: this.state.newData.slice().concat(res)
          })
        )
        .catch(err=>this.setState({requestSent: false}))
        this.setState({requestSent: true});
    }else{
      return true
    }
 })
  }
}
2020-07-22