您可能要创建一个布局组件
例:
// components/layout.js
import React from 'react'
import { initGA, logPageView } from '../utils/analytics'
export default class Layout extends React.Component {
componentDidMount () {
if (!window.GA_INITIALIZED) {
initGA()
window.GA_INITIALIZED = true
}
logPageView()
}
render () {
return (
<div>
{this.props.children}
</div>
)
}
}
然后,您可以使用Layout包装其他组件
例:
// pages/about.js
import Layout from '../components/layout'
export default () => (
<Layout>
<div>About us</div>
</Layout>
)
例:
// utils/analytics.js
import ReactGA from 'react-ga'
export const initGA = () => {
console.log('GA init')
ReactGA.initialize('UA-xxxxxxxxx-1')
}
export const logPageView = () => {
console.log(`Logging pageview for ${window.location.pathname}`)
ReactGA.set({ page: window.location.pathname })
ReactGA.pageview(window.location.pathname)
}
export const logEvent = (category = '', action = '') => {
if (category && action) {
ReactGA.event({ category, action })
}
}
export const logException = (description = '', fatal = false) => {
if (description) {
ReactGA.exception({ description, fatal })
}
}
我希望这有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句