代码之家  ›  专栏  ›  技术社区  ›  Oli C

如何在ReactRouter V4交换机设置中使用Google Analytics

  •  0
  • Oli C  · 技术社区  · 7 年前

    我试图在我的React单页应用程序中实现Google Analytics,但要做到这一点,我知道我需要使用 history 道具我正在使用开关设置,这似乎不起作用。

    <Switch history={history}>
        <Route exact path="/" component={place}/>
        <Route path="/about" component={otherplace}/>
        <Route component={error}/>
    </Switch>
    

    如果我改变主意 <Switch> <Router> 分析可以工作,但错误页面会在每个页面上呈现,当URL路径更改时,页面需要刷新。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Alain O'Dea    7 年前

    问题是错误组件位于所有路由上。

    试试这个: 添加一个独特的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>