React - How to get parameter value from query string?

后端 未结 30 1693
温柔的废话
温柔的废话 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:53

    If you aren't getting the this.props... you were expecting based on the other answers, you may need to use withRouter (docs v4):

    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 TwitterSsoButton = withRouter(ShowTheLocation)  
    
    // This gets around shouldComponentUpdate
    withRouter(connect(...)(MyComponent))
    
    // This does not
    connect(...)(withRouter(MyComponent))
    
    0 讨论(0)
  • 2020-11-22 10:54

    When using React hooks there is no access to access to this.props.location. To capture url parameters use window object.

    const search = window.location.search;
    const params = new URLSearchParams(search);
    const foo = params.get('bar');
    
    0 讨论(0)
  • 2020-11-22 10:55

    React router from v4 onwards no longer gives you the query params directly in its location object. The reason being

    There are a number of popular packages that do query string parsing/stringifying slightly differently, and each of these differences might be the "correct" way for some users and "incorrect" for others. If React Router picked the "right" one, it would only be right for some people. Then, it would need to add a way for other users to substitute in their preferred query parsing package. There is no internal use of the search string by React Router that requires it to parse the key-value pairs, so it doesn't have a need to pick which one of these should be "right".

    Having included that, It would just make more sense to just parse location.search in your view components that are expecting a query object.

    You can do this generically by overriding the withRouter from react-router like

    customWithRouter.js

    import { compose, withPropsOnChange } from 'recompose';
    import { withRouter } from 'react-router';
    import queryString from 'query-string';
    
    const propsWithQuery = withPropsOnChange(
        ['location', 'match'],
        ({ location, match }) => {
            return {
                location: {
                    ...location,
                    query: queryString.parse(location.search)
                },
                match
            };
        }
    );
    
    export default compose(withRouter, propsWithQuery)
    
    0 讨论(0)
  • 2020-11-22 10:55
    componentDidMount(){
        //http://localhost:3000/service/anas
        //<Route path="/service/:serviceName" component={Service} />
        const {params} =this.props.match;
        this.setState({ 
            title: params.serviceName ,
            content: data.Content
        })
    }
    
    0 讨论(0)
  • 2020-11-22 10:55

    Not the react way, but I beleive that this one-line function can help you :)

    const getQueryParams = () => window.location.search.replace('?', '').split('&').reduce((r,e) => (r[e.split('=')[0]] = decodeURIComponent(e.split('=')[1]), r), {});
    

    Example:
    URL:  ...?a=1&b=c&d=test
    Code:  

    >  getQueryParams()
    <  {
         a: "1",
         b: "c",
         d: "test"
       }
    
    0 讨论(0)
  • 2020-11-22 10:56

    As far as I know there are three methods you can do that.

    1.use regular expression to get query string.

    2.you can use the browser api. image the current url is like this:

    http://www.google.com.au?token=123
    

    we just want to get 123;

    First

     const query = new URLSearchParams(this.props.location.search);
    

    Then

    const token = query.get('token')
    console.log(token)//123
    

    3. use a third library called 'query-string'. First install it

    npm i query-string
    

    Then import it to the current javascript file:

     import queryString from 'query-string'
    

    Next step is to get 'token' in the current url, do the following:

    const value=queryString.parse(this.props.location.search);
    const token=value.token;
    console.log('token',token)//123
    

    Hope it helps.

    Updated on 25/02/2019

    1. if the current url looks like the following:

    http://www.google.com.au?app=home&act=article&aid=160990

    we define a function to get the parameters:

    function getQueryVariable(variable)
    {
            var query = window.location.search.substring(1);
            console.log(query)//"app=article&act=news_content&aid=160990"
            var vars = query.split("&");
            console.log(vars) //[ 'app=article', 'act=news_content', 'aid=160990' ]
            for (var i=0;i<vars.length;i++) {
                        var pair = vars[i].split("=");
                        console.log(pair)//[ 'app', 'article' ][ 'act', 'news_content' ][ 'aid', '160990' ] 
            if(pair[0] == variable){return pair[1];}
             }
             return(false);
    }
    

    We can get 'aid' by :

    getQueryVariable('aid') //160990
    
    0 讨论(0)
提交回复
热议问题