react,react-router单页面网站,cnzz/友盟统计怎么做?

目前的做法:

直接把统计代码放在index.html里面;
问题:不能统计到路由跳转过程中的url;

<script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan style='display:none;' id='cnzz_stat_icon_1258575107'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s5.cnzz.com/stat.php%3Fid%3D1258575107' type='text/javascript'%3E%3C/script%3E"));</script>

vue的写法

网上找到一个关于vue的cnzz统计的代码写法,求react项目怎么写比较好?

<template>  
  <router-view></router-view>  
</template>  
  
<script>  
export default {  
  name: 'app',  
  mounted () {  
    const script = document.createElement('script')  
    script.src = 'https://s95.cnzz.com/z_stat.php?id=1111111111&web_id=1111111111'  
    script.language = 'JavaScript'  
    document.body.appendChild(script)  
  },  
  watch: {  
    '$route' () {  
      if (window._czc) {  
        let location = window.location  
        let contentUrl = location.pathname + location.hash  
        let refererUrl = '/'  
        window._czc.push(['_trackPageview', contentUrl, refererUrl])  
      }  
    }  
  }  
}  
</script>  
阅读 6.5k
3 个回答
import {getMaidianTrendsBi} from "./utils/maidianBi";
const _hmt = window._hmt || []

  componentDidMount() {
  getMaidianTrendsBi();
   history.listen((location, action) => {
        _hmt.push(['_trackPageview', location.pathname]);
        getMaidianTrendsBi();
      })
  }

我不知道有没有钩子函数哈,有几种笨办法

一种是,在每个页面容器的componentDidMount里面单独写一下,这也可以吧

另一种是,再封装一下路由的那部分组件,比如 link啊 router.push redirect啊这类方法或组件,都可以自己封装下,吧跳转链接一参数形式穿进去,再用友盟的方法

还有一种就是可以用高阶组件包一下,每次都执行下高阶组件里面的方法,用来把当前的url push一下,这个和第一种差不多吧

新手上路,请多包涵

其实有必要考虑每个url下面的跳转吗?这不是就造成了重复统计,一个用户打开一个网站产生一次统计计算不是很正常吗?反而是非单页应用还要努力搞成页面跳转的时候只计算一次

推荐问题