简体   繁体   English

如何在 reactjs 中获取 url 参数

[英]How to get url parameters in reactjs

I have two components: App and Contact .我有两个组件: AppContact I just want to print the id on contacts page that I'm passing in the route, but when I console.log(this.props) in my contact component, it's showing an empty object.我只想在路由中传递的联系人页面上打印 id,但是当我在联系人组件中使用console.log(this.props)时,它显示一个空的 object。

import React from "react";
import Contact from "./Contact";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

class App extends React.Component {
  render() {
    return (
      <Router>
        <ul>
          <li>
            <Link exact to="/">
              Home
            </Link>
          </li>
          <li>
            <Link to={"/contact/id=" + 5}>contact us</Link>
          </li>
        </ul>

        <Route exact path="/">
          Home
        </Route>

        <Route path="/contact">
          <Contact />
        </Route>
      </Router>
    );
  }
}

export default App;
import React from "react";

class Contact extends React.Component {
  render() {
    {console.log(this.props);}
    return <div>contact page</div>;
  }
}

export default Contact;

how to console.log(this.props.match) ?如何console.log(this.props.match)

You could pass it into the Contact component like so:您可以将其传递给Contact组件,如下所示:

<Route path="/contact">
    <Contact id={5}/>
</Route>

and inside of your Contact component:在您的Contact组件内部:

If you are using classes如果您正在使用课程

this.props.id

If you are using functions如果您正在使用函数

function Contact({id, ...props}){
// id === 5
}

It is worth noting that this is still javascript and you could get the URL parameters the same way you would in vanilla JS like so: (if you wanted to, although it is not advised):值得注意的是,这仍然是 javascript,您可以像在 vanilla JS 中一样获得 URL 参数:(如果您愿意,尽管不建议这样做):

let id = (new URL(window.location.href)).searchParams.get('id');

Hope this helps,希望这可以帮助,

You're declaring your parameters incorrectly您错误地声明了参数

<Route path='/foo/:bar' component={Foo} />

And inside FooFoo里面

const Foo = ({ match }) =>{
    const = { params:{bar} } = match

    console.log(bar)
}

If you access like /foo/content bar will assert to content如果您访问喜欢/foo/content bar将断言content

I figured it out.我想到了。 I wrapped my HOC with withRouter() and the problem gets solved:)我用withRouter()包裹了我的 HOC,问题就解决了:)

Dead simple way two liner solution which will work for regardless of clsss & functional components死简单的方法两个班轮解决方案,适用于任何类和功能组件

const params = new URLSearchParams(window.location.search); // add on top under import
console.log(params.get('catid'));

I literally don't know why its not mentioned我真的不知道为什么没有提到

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

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