在React-Router中监听URL更改

时间:2020-07-08 15:24:36

标签: reactjs react-router

我正在尝试为URL更改添加侦听器,以便将其推送到GTM数据层。我目前的方法是将其添加到主要的应用程序组件中:

componentDidMount() {
    this.props.history.listen( (location, action) => {
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({
       'event': 'Pageview',
       'pagePath': location.pathname,
       'pageTitle': location.pathname
      });
    })
  }

或在创建历史记录时:

const history = createHistory();

history.listen((location, action) => {
      debugger;
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({
       'event': 'Pageview',
       'pagePath': location.pathname,
       'pageTitle': location.pathname
      });
});

render(
    <Root store={store} history={history} />,
    document.getElementById('root')
);

在这两种情况下,我都取得了部分成功-dataLayer包含除初始页面之外的所有页面视图-直接在浏览器导航栏中输入,或者当页面从付款页面重定向时-然后此页面视图未推送到dataLayer。 还有其他方法可以收听此初始路线吗? 这非常重要,特别是对于成功付款后捕获到thankYou页面的重定向。

0 个答案:

没有答案