Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

javascript - Save and restore window y position in Next js / React

I'm using nextjs Link with shallow and replace properties to change url from /author to /author?book=234523452 when the query is detected page conditionally hides an InfiniteScroll component and show a component with a single book instead. Single book component has a "X" to go back (also wrapped within a Link) so to show again the InfiniteScrollComponent.

What I'm trying to do is save the current window Y on query (single book) and when the "X" gets clicked move to that stored position via useState.

I'd like to mention that unfortunately scroll={false} doesn't work for my case.

this is my page relevant code:

const [scrollPos, setScrollPos] = useState()

const readUrl = (url, bool) => {
  if (url){
    setScrollPos(window.pageYOffset || document.documentElement.scrollTop)
    setUrlNow(url)
  }else{
    router.events.on('routeChangeComplete', () => {
      if (typeof window !== "undefined") {
        //setTimeout(function(){
          window.scrollTo(0,scrollPos)
        //},200)
      }
    })
  }
  setToggle(bool)
  
  return
}

if (url) means it's routing from /author (so with InfiniteScroll component) to /author?book=234523452 (with single book), else means the "X" got clicked basically and so is routing back to /author

The setTimeout(function() seems to work most of the times but not always, and also adds an ugly moving effect to it


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can set scrollPos for reach retainedComponent and there is detailed guidance here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...