问题
I have a condition inside my lifecycle method of user Page such that if the user enters an URL with certain parameters such as somePage.com/user/1
will fetch the data of the user with ID 1, however, if the user enters the URL as somePage.com/user/1ABC
then im routing them to a custom 404 page. My issue is when im in the 404-page clicking on the back button will take me back to the page with URL somePage.com/user/1ABC
and then will route back to the same 404-page as the URL param met a condition in the lifecycle method of the user page.
I would like to route the user to some other URL if they land up in the 404-page and click on the back button of the browser.
回答1:
Router.push will add the new URL into the history stack, however, Router.replace will redirect to the 404-page without adding a new URL entry into the history stack. So the back button will redirect to the last successful entry in the history stack, https://nextjs.org/docs/api-reference/next/router#routerreplace gives a clear example.
来源:https://stackoverflow.com/questions/59926039/nextjs-404-page-back-button-returns-back-to-404-page