0

我正在尝试将使用 ReactJS 制作的个人网站连接到 Google Analytics。我已按照教程进行操作,但仍然无法看到活动用户(当我访问本地主机上的站点或使用 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;

4

1 回答 1

0

您没有收听位置更改。试试这个方法。添加一个名为 的组件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,如下所示。

应用程序.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;
于 2020-09-25T06:18:44.740 回答