React - How to get parameter value from query string?

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

提交回复
热议问题