我试图在我的React单页应用程序中实现Google Analytics,但要做到这一点,我知道我需要使用 history 道具我正在使用开关设置,这似乎不起作用。
history
<Switch history={history}> <Route exact path="/" component={place}/> <Route path="/about" component={otherplace}/> <Route component={error}/> </Switch>
如果我改变主意 <Switch> 到 <Router> 分析可以工作,但错误页面会在每个页面上呈现,当URL路径更改时,页面需要刷新。
<Switch>
<Router>
问题是错误组件位于所有路由上。
试试这个: 添加一个独特的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>