如何检查 useRouter 是否可以在 nextjs 应用程序中使用 router.back()

Pho*_* Vũ 5 next.js

  • 我正在为我的应用程序使用 next js,并且在路由到应用程序的上一个路由时遇到一些问题。我知道有类似的功能router.back(),但我不知道是否可以从当前页面返回。
  • 我读到我们可以检查history.action !== 'POP',但现在我检查使用 console.log(history) 时历史记录没有操作属性

我正在使用下一个/路由器。

Gee*_*Gee 10

Update Dec 2023:

It appears the history.state.idx method no longer works, currently this is doable with the following:

if (window.history?.length) {
   router.back();
} else {
   router.replace(href || "/");
}
Run Code Online (Sandbox Code Playgroud)

Original:

Way too late to be useful but for the next person that comes along: If I read your question correctly, you're wanting to know if there is something in the navigation stack that you can navigate back to - and you want to do something else if there is no history.

You can use window.history.state to get a glimpse; although it doesn't give you clear access to the history stack the state has an "idx" property that is incremented when a location is added to the history stack. This means that if window.history.state.idx is zero there's nothing in the history stack, if it's bigger than zero then there is something in the history stack and you can navigate back.

An example for navigating back if you can or doing something else if not:

if (window.history.state && window.history.state.idx > 0) {
    router.back();
} else {
    // Do something else              
}
Run Code Online (Sandbox Code Playgroud)