如何在 Next.js 应用程序目录中使用 next/navigation 的函数中访问 router.asPath ?

Muh*_*mer 9 javascript reactjs next.js

import { useRouter } from "next/navigation";


const router = useRouter()

const refreshData = () => {
router.replace(router.asPath);
Run Code Online (Sandbox Code Playgroud)

}

我尝试使用下一个/路由器但没有成功

bra*_*ipt 12

在 Next.js 13 的新应用程序目录方案中,useRouter工作方式不同。您需要usePathnamehttps ://beta.nextjs.org/docs/upgrade-guide#step-5-migration-routing-hooks

值得注意的是,还有一个未解决的问题,在某些情况下,useRouter它不能usePathname按预期工作(特别是在 router.events 周围)。

但也正如 @YoussoufOumar 所指出的,它看起来不像您正在使用 app dir,所以您想从next/router.