React - How to get parameter value from query string?

后端 未结 30 1678
温柔的废话
温柔的废话 2020-11-22 10:22

How can I define a route in my routes.jsx file to capture the __firebase_request_key parameter value from a URL generated by Twitter\'s single sign on process a

相关标签:
30条回答
  • 2020-11-22 10:57

    React Router v5.1 introduced hooks:

    For

    <Route path="/posts/:id">
      <BlogPost />
    </Route>
    

    You can access params / id with hook:

    const { id } = useParams();
    

    More here.

    0 讨论(0)
  • 2020-11-22 10:57

    In React Router v4 only withRoute is correct way

    You can get access to the history object’s properties and the closest 's match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

    import React from 'react'
    import PropTypes from 'prop-types'
    import { withRouter } from 'react-router'
    
    // A simple component that shows the pathname of the current location
    class ShowTheLocation extends React.Component {
      static propTypes = {
        match: PropTypes.object.isRequired,
        location: PropTypes.object.isRequired,
        history: PropTypes.object.isRequired
      }
    
      render() {
        const { match, location, history } = this.props
    
        return (
          <div>You are now at {location.pathname}</div>
        )
      }
    }
    
    // Create a new component that is "connected" (to borrow redux
    // terminology) to the router.
    const ShowTheLocationWithRouter = withRouter(ShowTheLocation)
    

    https://reacttraining.com/react-router/web/api/withRouter

    0 讨论(0)
  • 2020-11-22 10:57

    in typescript, see snippet below for example:

    const getQueryParams = (s?: string): Map<string, string> => {
      if (!s || typeof s !== 'string' || s.length < 2) {
        return new Map();
      }
    
      const a: [string, string][] = s
        .substr(1) // remove `?`
        .split('&') // split by `&`
        .map(x => {
          const a = x.split('=');
          return [a[0], a[1]];
        }); // split by `=`
    
      return new Map(a);
    };
    

    in react with react-router-dom, you can do

    const {useLocation} from 'react-router-dom';
    const s = useLocation().search;
    const m = getQueryParams(s);
    

    see example below

    // below is the transpiled and minified ts functions from above
    const getQueryParams=t=>{if(!t||"string"!=typeof t||t.length<2)return new Map;const r=t.substr(1).split("&").map(t=>{const r=t.split("=");return[r[0],r[1]]});return new Map(r)};
       
    // an example query string
    const s = '?arg1=value1&arg2=value2'
    
    const m = getQueryParams(s)
    console.log(m.get('arg1'))
    console.log(m.get('arg2'))
    console.log(m.get('arg3')) // does not exist, returns undefined

    0 讨论(0)
  • 2020-11-22 10:58

    When you work with react route dom then will empty object with for match but if you do the following code then it will for es6 component as well as it works directly for function component

    import { Switch, Route, Link } from "react-router-dom";
    
    <Route path="/profile" exact component={SelectProfile} />
    <Route
      path="/profile/:profileId"
      render={props => {
        return <Profile {...props} loading={this.state.loading} />;
      }}
    />
    </Switch>
    </div>
    

    This way you can get props and match params and profile id

    This worked for me after a lot of research on es6 component.

    0 讨论(0)
  • 2020-11-22 10:59

    React Router v4 no longer has the props.location.query object (see github discussion). So the accepted answer will not work for newer projects.

    A solution for v4 is to use an outside library query-string to parse the props.location.search

    const qs = require('query-string');
    //or
    import * as qs from 'query-string';
    
    console.log(location.search);
    //=> '?foo=bar'
    
    const parsed = qs.parse(location.search);
    console.log(parsed);
    //=> {foo: 'bar'}
    
    0 讨论(0)
  • 2020-11-22 10:59

    React Router 5.1+

    5.1 introduced various hooks like useLocation and useParams that could be of use here.

    Example:

    <Route path="/test/:slug" component={Dashboard} />
    

    Then if we visited say

    http://localhost:3000/test/signin?_k=v9ifuf&__firebase_request_key=blablabla
    

    You could retrieve it like

    import { useLocation } from 'react-router';
    import queryString from 'query-string';
    
    const Dashboard: React.FC = React.memo((props) => {
        const location = useLocation();
    
        console.log(queryString.parse(location.search));
    
        // {__firebase_request_key: "blablabla", _k: "v9ifuf"}
    
        ...
    
        return <p>Example</p>;
    }
    
    0 讨论(0)
提交回复
热议问题