首页 > 解决方案 > 如何使用自定义历史对象监听主 App 组件中的路由更改?

问题描述

我有一个标题出现在我网站 95% 的页面中,所以我将它安装在我的主 App 组件中。对于其他 5% 的页面,尽管我需要它消失。

我想一个好方法是根据当前路由将状态从 true 更改为 false,并且该状态将确定标头是否安装。

起初我尝试仅将window.location.href其用作useEffect依赖项,但这似乎不起作用。我已经阅读了有关收听历史位置的选项,但我不断收到Cannot read property 'history' of undefined. 我认为这可能是因为我正在使用自定义历史组件,或者可能是因为我尝试在我的主 App 组件中这样做?没有把握。

这是我的历史对象:

import { createBrowserHistory } from 'history'; 
export default createBrowserHistory();

Router像这样使用它:

<Router history={history}>

CONDITIONAL COMPONENT

  <Switch>
    ...routes
  </Switch>
</Router>

这就是我尝试听的方式,history我的自定义历史对象在哪里 const MyHistory = useHistory(history)

  useEffect(() => {
      return MyHistory.listen((location) => {
          console.log(`You changed the page to: ${location.pathname}`)
      })
  },[MyHistory])

标签: javascriptreactjsreact-router

解决方案


您正在尝试在呈现提供程序的组件中使用 useHistory Router。为了使 useHistory 工作,它需要在层次结构中具有更高的路由器。

所以要么你用路由器包装 App 组件,比如

export default () => (
    <Router history={history}><App /><Router>
)

或者由于您定义了自定义历史记录,您可以直接使用它而不使用 useHistory

useEffect(() => {
      return history.listen((location) => {
          console.log(`You changed the page to: ${location.pathname}`)
      })
  },[])

推荐阅读