繁体   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