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