在启用SSR的NextJs应用程序中注册路由更改事件时遇到了麻烦。
我正在使用GTM中的历史更改事件触发器。
使用react-gtm-module来初始化Google Tag Manager。
问题:当我从页面/product/123/导航到像/product/124/这样的页面时,事件不会触发,但是当挂载时,事件会随着路由(例如www.site.com/product/123)而触发。
产品页面:
return (
<div>
<div>{props.title}</div>
<Link href="/product/[pid]" as={`/product/124`}>
<a>Another product (should trigger event here, but doesn't)</a>
</Link>
</div>
)
我尝试将这段代码添加到 _app.js 中的 componentDidMount 函数中。
import Router from 'next/router';
...
componentDidMount () {
...
if (process.browser) {
Router.onRouteChangeComplete = url => {
window.history.pushState({}, document.title, url);
};
}
在NextJs中,正确的做法是什么?