簡體   English   中英

獲取 class 組件路由器 V6 中的 url 參數反應

[英]get the url params in a class component router V6 react

我已將我的項目從路由器 v5 更新到 v6。 現在我無法使用queryString.parse(this.window.location)讀取 URL 參數

有沒有辦法在 class 組件路由器 V6 中獲取參數? 以下是我的代碼。

應用程序.js

function App(){
    return(
     <Routes>
       <Route path="/bookingSummary" element={<BookingSummary/>}/>
     </Routes>
    )}

bookingSummary.js(類組件)

componentDidMount() {
 movieInfo = queryString.parse(this.window.location)
}

根據queryString是什么,我認為您可能只需要從window.location object 傳遞search字符串,例如queryString.parse(this.window.location.search)

您應該使用useSearchParams掛鈎來訪問 queryString 參數 object。 如果您使用的是基於類的組件,您仍然需要轉換為 React function 組件才能使用 React 掛鈎,或者使用自定義的withRouter實現來訪問 queryString 參數並將其也作為道具注入。

例子:

import { useSearchParams, /* other hooks */ } from 'react-router-dom';

const withRouter = WrappedComponent => props => {
  const [searchParams, setSearchParams] = useSearchParams();
  // etc... other react-router-dom v6 hooks

  return (
    <WrappedComponent
      {...props}
      {...{ searchParams, setSearchParams, /* other injected props */} }
    />
  );
};

裝飾BookingSummary組件。

export default withRouter(BookingSummary);

訪問注入的道具。

componentDidMount() {
  const { searchParams } = this.props;
  const movieInfo = searchParams.get("movieInfo");

  ...
}

暫無
暫無

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

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