[英]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.