【问题标题】:Make 2nd API calls when all contents are loaded (lazy loading) from the first API call in React js从 React js 中的第一个 API 调用加载所有内容(延迟加载)时进行第二次 API 调用
【发布时间】:2019-01-13 10:28:20
【问题描述】:

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

【问题讨论】:

  • 请包含您目前编写的代码并说明您遇到的问题。

标签: reactjs npm lazy-loading npm-lazy


【解决方案1】:

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

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

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

【讨论】:

【解决方案2】:

React.js 只是带有 JSX 风格的纯 javascript。您必须在容器上添加事件滚动,并在滚动到达终点时触发一个方法以在您的 API 上进行 GET 调用,就像在 React 外部一样。

【讨论】:

    猜你喜欢
    • 2020-09-11
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 2020-11-05
    • 2022-07-03
    相关资源
    最近更新 更多