正确设置React Router历史侦听器的位置

问题描述 投票:0回答:3

我正在尝试在最顶层设置历史监听器,以便每次位置更改时,都会执行一些代码(在我的案例中为Google Analytics跟踪)。

目前,我的App.js看起来像这样:

    render() {
        return (
            <BrowserRouter>
                <Switch>
                    <Route path="/" exact component={Home}/>
                    <Route path="/" component={MainLayout}/>
                </Switch>
            </BrowserRouter>
        );
    }

据我所知,我只能在history中使用BrowserRouter,但它只能有一个孩子,所以我只能把它放在Switch里面,但是我必须把它放在Switch下的每个组件里面,我不能这样做因为我希望它只运行一次。如果我只是在Switch下添加一个自定义组件而不将其包装到Router中,那么就没有历史了。

我应该改变什么来使它工作?是否有可能在history代码中获得App.js的实例?是否可以使用自定义组件或HOC实现?

reactjs react-router-v4 browser-history
3个回答
1
投票

你需要添加一个无条件渲染的Route。尝试这样的事情:

render() {
    return (
        <BrowserRouter>
            <React.Fragment>
                <Route component={HistoryListenerComponent}/>
                <Switch>
                    <Route path="/" exact component={Home}/>
                    <Route path="/" component={MainLayout}/>
                </Switch>
            </React.Fragment>
        </BrowserRouter>
    );
}

所以HistoryListenerComponent总是呈现,你可以从它的listen componentDidMount


0
投票

可以使用history包,而不是依赖于react路由器创建的默认包。

例如,使用history.listen

  history.listen((location) => {
    ReactGA.pageview(location.pathname + window.location.search);
  });

在我的例子中,我使用react-ga作为跨项目标准化GA Instrumentation的一种方式。


0
投票

发现最简单的选项是Update组件 - https://github.com/pshrmn/rrc/blob/master/docs/OnUpdate.md

© www.soinside.com 2019 - 2024. All rights reserved.