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.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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
}
})
}
}
回答2:
React.js is just plain javascript with JSX flavour. You have to add the event scroll on your container and trigger a method to make a GET call on your API when scroll reaches end exactly as outside React.