AppRouterではrouter.events
はサポートされていません。
以下の方法でページの変更ごとに処理を行うことができます。
app/_components/navigation-events.js
'use client'
import { useEffect } from 'react'
import { usePathname, useSearchParams } from 'next/navigation'
export function NavigationEvents() {
const pathname = usePathname()
const searchParams = useSearchParams()
useEffect(() => {
const url = `${pathname}?${searchParams}`
console.log(url)
// URLが変更された際に実行される処理
}, [pathname, searchParams])
return null
}
上記をlayout.js
に記述します。
app/layout.js
import { Suspense } from 'react'
import { NavigationEvents } from './components/navigation-events'
export default function Layout({ children }) {
return (
<html lang="en">
<body>
{children}
<Suspense fallback={null}>
<NavigationEvents />
</Suspense>
</body>
</html>
)
}