【问题标题】:How to use Google Analytics in a ReactRouter V4 Switch setup如何在 ReactRouter V4 Switch 设置中使用 Google Analytics
【发布时间】:2018-10-31 10:58:37
【问题描述】:
我正在尝试在我的 React 单页应用程序中实现 Google Analytics,但我知道我需要使用 history 道具。我正在使用 Switch 设置,这似乎不起作用。
<Switch history={history}>
<Route exact path="/" component={place}/>
<Route path="/about" component={otherplace}/>
<Route component={error}/>
</Switch>
如果我将 <Switch> 更改为 <Router> 分析工作,但错误页面会呈现在每个页面上,并且当 URL 路径更改时页面需要刷新。
【问题讨论】:
标签:
node.js
reactjs
google-analytics
react-router
【解决方案1】:
问题是错误组件在所有路由上。
试试这个:
添加一个独特的 404 错误路由:
<Route path='/404' component={error} />
将所有不匹配的路由路由到它:
<Redirect from='*' to='/404' />
这应该只在不存在的页面上显示错误组件。
这是一个可以做到这一点的开关:
<Switch history={history}>
<Route exact path="/" component={place}/>
<Route path="/about" component={otherplace}/>
<Route path='/404' component={error} />
<Redirect from='*' to='/404' />
</Switch>