简体   繁体   中英

How to dynamically change URL in a Next.js application without using <Link>?

I know it's possible to dynamically change the URL without refreshing the page by using <Link> ; however, is it possible to do so without <Link> ? For context, I'm trying to change the URL dynamically on a page to another one if a variable changes its value from false to true . The variable's value isn't dependent on a button being clicked on, so that's why I don't want to use <Link> . At the moment, I'm using window.top.location.href inside of a useEffect() , which gets the job done — but it's very clunky since the entire page reloads. Does anyone know how to achieve what I'm trying to do?

The following is what I'm currently doing:

useEffect(() => {
  if (status === true) {
    window.top.location.href='https://www.website.com'
  };
}, [status];

I figured out a solution. All I needed to do was swap out the line with window.top.location.href to router.push() . The following is the updated code that works as intended:

useEffect(() => {
  if (status === true) {
    router.push('https://www.website.com')
  };
}, [status];

想改URl而不刷新的原因是什么?

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