简体   繁体   中英

Changing the URL dynamically in Gatsby / React

Is there a function that I can use to change the page URL in the browser from a function when an action is taken?

I currently have a group of paginated pages. When you click to view another page, the component that has the list of pages changes with no page refresh and the scroll point moves to the top of the post list. Essentially my function just changes the contents of a component with the next page of data.

The desired behaviour for this is that the URL should also change when the data of a new page is requested and not cause a reload.

eg. If you're on Blog page 1 the URL will be

domain.com/blog/1/

and when you click the navigation it will scroll to the top of the page(which works fine) and change the URL without refresh or reload to

domain.com/blog/2/

I tried to use navigate() but this seems to cause the page to reload using the following code.

const [currentPage, setCurrentPage] = useState(pageNumber)

useEffect(() => {
  scrollTo('#posts')

  let url = `/blog/`

  if (currentPage !== 1) {
    url = `/blog/${currentPage}/`
  }

  navigate(URL)

},[currentPage])

Also, the pages exist and are generated on build already should you browse to them on /blog/1/ /blog/2/, I'm just after modifying the URL on pagination changes.

Figured it out in the end and this is all working in dev and using Gatsby's SSR

I created a React Hook called useUrlUpdate

export function useUrlUpdate(url) {
  if (typeof window !== `undefined` && typeof url !== `undefined`) {
    window.history.pushState({}, '', URL);
  }
  return
}

Then my function now looks like this

const urlUpdate = useUrlUpdate()
const [currentPage, setCurrentPage] = useState(pageNumber)

useEffect(() => {
  scrollTo('#posts')

  let url = `/blog/`

  if (currentPage !== 1) {
    url = `/blog/${currentPage}/`
  }

  useUrlUpdate(url)


},[currentPage])

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