I want to infinite scroll to fetch any items, the brief step is:
1) scroll at the end of screen.
2) use redux to update items pageIndex.
3) use componentDidUpdate
to catch this redux action.
4) append the fetch items to the end of items' array.
class InfiniteScroll extends React.Component {
componentDidMount() {
window.addEventListener("scroll", throttle(this.onScroll, 500), false);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.onScroll, false);
}
componentDidUpdate(preProps) {
if (props.pageindex === preProps.pageindex + 1)
fetchItems(...);
}
onScroll = () => {
if (
window.innerHeight + window.scrollY >=
document.body.offsetHeight - 100
) {
updatePage(...);
}
};
render() {
return <Component {...this.props} />;
}
}
The only problem with this code is when updatePage
executes once, the fetchItems
can not follow it immediately.