简体   繁体   中英

Change route without reloading page with Next.js

Whenever the user clicks on the continue button, a function is fired and in that function, I call:

push("/signup/page-2", undefined, { shallow: true });

All dynamic routes that looks like /signup/[page].js that returns <Component />

I also have a /signup/index.js that returns <Component />

The Problem is:

The page reloads and all state is cleared each time push("/signup/page-2", undefined, { shallow: true }); is called.

It's also worth mentioning that this app was a CRA with react-router-dom app that was converted to a next.js app

You got it all wrong about shallow-routing . Shallow-routing works for the same page URL and generally, you will update the query string parameters for the same page and the updated value of query params will be available through the router .

router.push('/signup/[page]', '/signup/page-1') will push the new URL path and will navigate to a complete different page from /signup/ . That is why shallow-routing doesn't work here and the state value resets.

In the pages directory /signup/[page].js and /signup/index.js are two completely different files in the file system. If you try to navigate between them with shallow-routing it will not work.

Solution

You don't need another dynamic route like /signup/[page] here, you can update the page param through query string and keep the same URL path. In /signup/index.js page you can get the updated value of the query param and work on it.

router.push({
   pathname: '/signup',
   query: {
      pageId: "page-1"  // update the query param
   }
}, undefined, { shallow: true})


// you have access to the updated value of pageId through router.query.pageId

const currPage = router.query.pageId

Ignore next router for this task, just use JavaScript to change the URL instead - components will not reload or be affected.

window.history.pushState(null, 'Page Title', '/newUrl'); (null is stateData).

For example:
You are on a users profile page localhost.com/john and you click on their post with the id 13983 :

function onPostClicked(post){
  showPost(post);
  window.history.pushState(null, 'Post by John', '/john/p/13983');
}

Then when they click away from the post you can return back to the original URL:

function onPostClosed(){
  hidePost();
  window.history.pushState(null, 'John', '/john');
}

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