簡體   English   中英

如何使用自定義歷史記錄 object 在我的主 App 組件中收聽路由更改?

[英]How can I listen to route change in my main App component, using a custom history object?

我有一個 header 出現在我網站 95% 的頁面中,所以我將它安裝在我的主要應用程序組件中。 對於其他 5% 的頁面,盡管我需要它消失。

我想一個好方法是根據當前路線將 state 從 true 更改為 false,並且 state 將確定 header 是否安裝。

起初我嘗試僅使用window.location.href作為useEffect依賴項,但這似乎不起作用。 我已經閱讀了有關收聽歷史記錄位置的選項,但我不斷收到Cannot read property 'history' of undefined 我認為這可能是因為我正在使用自定義歷史組件,或者可能是因為我嘗試在我的主 App 組件中這樣做? 沒有把握。

這是我的歷史 object:

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

我在我的Router中使用它是這樣的:

<Router history={history}>

CONDITIONAL COMPONENT

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

這就是我嘗試聽的方式,其中history是我的自定義歷史 object const MyHistory = useHistory(history)

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

您正在嘗試在呈現作為 Provider 的Router的組件中使用 useHistory。 為了使 useHistory 工作,它需要在層次結構中具有更高的路由器。

所以要么你用路由器包裝 App 組件,比如

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

或者由於您定義了自定義歷史記錄,您可以直接使用它而不使用 useHistory

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

這就是我如何控制我的應用程序中的每一個路線變化。 我創建了一個組件來偵聽useLocation給出的pathname屬性

import { useEffect } from "react";
import { useLocation } from "react-router-dom";

export default function AppScrollTop() {
  const { pathname } = useLocation();

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

  return null;
}

然后我把組件放在<Router>

<BrowserRouter>
   <AppScrollTop />
   <Switch>
     <Route path="/login" component={Login} />
   </Switch>
</BrowserRouter>

我希望這有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM