简体   繁体   中英

Validate route on click and before the page-load

Within Next.js, how would I validate a route before its loaded?

As per the API docs , routeChangeStart is triggered before route change, however, I am unable to cancel the event once triggered.

  useEffect(() => {
    events.on("routeChangeStart", routerChangeHandler);
    return (() => events.off("routeChangeStart", routerChangeHandler));
  });

  const routerChangeHandler = (url) => {
    if(/* check something */){
      // stop the new page load and stay on the page
      return false;
    }
  };

I think you should do something like this: Next JS: Warn User for Unsaved Form before Route Change

You can try throwing an error to cancel the navigation:

  events.on('routeChangeStart', () => {
    throw new Error('AbortError');
  });

Also you can try to dispatch routeChangeError :

 events.emit('routeChangeError');

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