如何从RouteComponentProps获取数据

时间:2019-11-29 08:03:17

标签: reactjs

我想使用import { RouteComponentProps } from "react-router-dom";中的信息。我知道该模块可以提供有关我们URL的信息,但是我无法设置它。如何在我的React组件中获取有关URL的数据?

import { RouteComponentProps } from 'react-router-dom';
const App = () => {
  console.log(here i want to get information about my URL);
  return (
    <div className="main">
    </div>
  );
}

export default App;

2 个答案:

答案 0 :(得分:0)

我想您可以像这样使用它:

const App = ({ match }: RouteComponentProps<any>) => {

假设您的路由是这样的:

鉴于RouteComponentProps的定义如下:

export interface RouteComponentProps<Params extends { [K in keyof Params]?: string } = {}, C extends StaticContext = StaticContext, S = H.LocationState> {
  history: H.History;
  location: H.Location<S>;
  match: match<Params>;
  staticContext?: C;
}

然后您可以理解,我提取的匹配项包含url数据供您检查。因此,假设您的网址是http://foo/your-component/bar

this.props: all properties including routing-related
this.props.match.params.param1: prints 'bar'

答案 1 :(得分:0)

如果在功能组件中使用,则可以简单地使用react挂钩。

代码如下

import { useParams} from "react-router"; 
    import { useLocation} from "react-router";
    const App = () => {
       let location = useLocation();
        console.log(location);  // for url location info
      let params = useParams();
       console.log(params );  // for params information
      return (
        <div className="main">
        </div>
      );
    }

    export default App;