Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 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

question from:https://stackoverflow.com/questions/65855014/save-and-restore-window-y-position-in-next-js-react

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...