我有一些.json文件。我需要将浏览器中第一个.json文件中的所有数据显示为延迟加载。当所有内容都从第一个.json文件加载 时(当用户scoll到页面末尾时), 我需要对第二个.json进行API调用 ) 。我不应该一次进行所有API调用。如何使用react js做到这一点。
利用javascript scrolleventListener并计算窗口滚动高度,以触发异步调用。
scroll
请在构造函数中绑定必要的方法并定义状态。这是代码
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 } }) } }