简体   繁体   中英

React infinite scrolling mechanism

I need to implement an infinite mechanism of scrolling in the react project, and when I reach the bottom of the page to add more images to my images array in the Gallery component.

the problem is that it happens only ones, only in the first scrolling to the bottom of the page.

adding an image of my functions: scrolling functions

thanks for helping!!

you should listen for scrool event in componentDidMount and only removeListner in componentDidMount , also I noticed your removing the listener in your track scrolling function isn't that just counterproductive? try removing that line

What you can do is create a custom hook for that infinite scroll behaviour. That way you can easily reuse the code for multiple places in your application. You have to think about input / output for that hook:

  • input:

    1. callback to fetch more items,
    1. element to be monitored for when it reaches the bottom for the callback
  • output

    1. if list is loading or not (so you can show the spinner)

You can rely on intersection observer to be doing the heavy lifting for you. It should be normally supported on modern browsers.

I recently created an article on the subject if you want to check it here that covers it in full detail

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM