问题描述
我正在尝试将使用ReactJS创建的个人网站连接到Google Analytics(分析)。我已经按照this教程进行操作,但是仍然看不到活跃的用户(当我在本地主机上访问网站或使用netlify部署网站时)。
这是我的app.js:
import React,{useEffect} from 'react';
import Courses from './containers/Courses/Courses';
import Home from './containers/Home/Home';
import {Route,Switch,Redirect} from 'react-router-dom';
import Layout from './hoc/Layout/Layout';
import About from './containers/About/About';
import ContactPage from './containers/ContactPage/ContactPage';
import Projects from './components/Projects/Projects';
import ReactGa from 'react-ga';
const App = () => {
useEffect(() => {
document.title = "Dhruv Mittal";
ReactGa.initialize('UA-XXXXXXXXX-X');
//Report page view
ReactGa.pageview(window.location.pathname + window.location.search);
},[]);
let routes = (
<Switch>
<Route path="/about" component={About}/>
<Route path="/projects" component={Projects}/>
<Route path="/courses" component={Courses}/>
<Route path="/contact" exact component={ContactPage}/>
<Route path="/" component={Home}/>
<Redirect to='/'/>
</Switch>
);
return (
<div>
<Layout>
{routes}
</Layout>
</div>
);
}
export default App;
解决方法
您没有听位置更改。尝试这种方式。添加一个名为GAListener
的组件,该组件可以监听history
对象的位置变化。
GaListener.js
import React from 'react';
import ReactGA from 'react-ga';
import { withRouter } from 'react-router-dom';
class GAListener extends React.Component {
componentDidMount() {
ReactGA.initialize("UA-XXXXXXXXX-X");
this.sendPageView(this.props.history.location);
this.props.history.listen(this.sendPageView);
}
sendPageView = location => {
ReactGA.set({ page: location.pathname });
ReactGA.pageview(location.pathname);
};
render() {
return this.props.children;
}
}
export default withRouter(GAListener);
现在将Route
组件包装到GAListener
组件中,如下所示。
App.js
const App = () => {
let routes = (
<GAListener>
<Switch>
<Route path="/about" component={About}/>
<Route path="/projects" component={Projects}/>
<Route path="/courses" component={Courses}/>
<Route path="/contact" exact component={ContactPage}/>
<Route path="/" component={Home}/>
<Redirect to='/'/>
</Switch>
</GAListener>
);
return (
<div>
<Layout>
{routes}
</Layout>
</div>
);
}
export default App;