简体   繁体   English

获取 class 组件路由器 V6 中的 url 参数反应

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

I've updated my project from router v5 to v6.我已将我的项目从路由器 v5 更新到 v6。 now I can't read the URL params using queryString.parse(this.window.location)现在我无法使用queryString.parse(this.window.location)读取 URL 参数

is there a way to get the parameters in a class component router V6?有没有办法在 class 组件路由器 V6 中获取参数? following is my code.以下是我的代码。

App.js应用程序.js

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

bookingSummary.js(class component) bookingSummary.js(类组件)

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

Depending on what queryString is I think you might only need to pass the search string from the window.location object, eg queryString.parse(this.window.location.search) .根据queryString是什么,我认为您可能只需要从window.location object 传递search字符串,例如queryString.parse(this.window.location.search)

You should use the useSearchParams hook though to access the queryString parameters object.您应该使用useSearchParams挂钩来访问 queryString 参数 object。 If you are using a class-based component you'll still need to either convert to a React function component in order to use the React hooks, or utilize the custom withRouter implementation to access the queryString params and inject that also as props.如果您使用的是基于类的组件,您仍然需要转换为 React function 组件才能使用 React 挂钩,或者使用自定义的withRouter实现来访问 queryString 参数并将其也作为道具注入。

Example:例子:

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 */} }
    />
  );
};

Decorate the BookingSummary component.装饰BookingSummary组件。

export default withRouter(BookingSummary);

Access the injected props.访问注入的道具。

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

  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM