从React js中的第一个API调用加载所有内容(延迟加载)后,进行第2个API调用 [英] Make 2nd API calls when all contents are loaded (lazy loading) from the first API call in React js

查看:288
本文介绍了从React js中的第一个API调用加载所有内容(延迟加载)后,进行第2个API调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some .json files. I need to show all the data from the first .json file in browser as lazy loading.I need to make API call to the second .json when all contents are loaded from the first .json file (when user scoll to end of the page). I should not make all API call at a time. How to do this using react js.

推荐答案

使用javascript scroll eventListener并计算窗口滚动高度以触发异步调用.

Make use of javascript scroll eventListener and calculate the window scroll height in order to trigger the async call.

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

Please bind the necessary method in the constructor and define state respectively. Here is the code

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
    }
 })
  }
}

这篇关于从React js中的第一个API调用加载所有内容(延迟加载)后,进行第2个API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆