How do you programmatically update query params in react-router?

后端 未结 8 2037
Happy的楠姐
Happy的楠姐 2020-11-29 21:41

I can\'t seem to find how to update query params with react-router without using . hashHistory.push(url) doesn\'t seem to register que

相关标签:
8条回答
  • 2020-11-29 22:21

    Within the push method of hashHistory, you can specify your query parameters. For instance,

    history.push({
      pathname: '/dresses',
      search: '?color=blue'
    })
    

    or

    history.push('/dresses?color=blue')
    

    You can check out this repository for additional examples on using history

    0 讨论(0)
  • 2020-11-29 22:21

    Using query-string module is the recommended one when you need a module to parse your query string in ease.

    http://localhost:3000?token=xxx-xxx-xxx

    componentWillMount() {
        var query = queryString.parse(this.props.location.search);
        if (query.token) {
            window.localStorage.setItem("jwt", query.token);
            store.dispatch(push("/"));
        }
    }
    

    Here, I am redirecting back to my client from Node.js server after successful Google-Passport authentication, which is redirecting back with token as query param.

    I am parsing it with query-string module, saving it and updating the query params in the url with push from react-router-redux.

    0 讨论(0)
  • 2020-11-29 22:22
        for react-router v4.3, 
    
     const addQuery = (key, value) => {
      let pathname = props.location.pathname; 
     // returns path: '/app/books'
      let searchParams = new URLSearchParams(props.location.search); 
     // returns the existing query string: '?type=fiction&author=fahid'
      searchParams.set(key, value);
      this.props.history.push({
               pathname: pathname,
               search: searchParams.toString()
         });
     };
    
      const removeQuery = (key) => {
      let pathname = props.location.pathname; 
     // returns path: '/app/books'
      let searchParams = new URLSearchParams(props.location.search); 
     // returns the existing query string: '?type=fiction&author=fahid'
      searchParams.delete(key);
      this.props.history.push({
               pathname: pathname,
               search: searchParams.toString()
         });
     };
    
    
     ```
    
     ```
     function SomeComponent({ location }) {
       return <div>
         <button onClick={ () => addQuery('book', 'react')}>search react books</button>
         <button onClick={ () => removeQuery('book')}>remove search</button>
       </div>;
     }
     ```
    
    
     //  To know more on URLSearchParams from 
    [Mozilla:][1]
    
     var paramsString = "q=URLUtils.searchParams&topic=api";
     var searchParams = new URLSearchParams(paramsString);
    
     //Iterate the search parameters.
     for (let p of searchParams) {
       console.log(p);
     }
    
     searchParams.has("topic") === true; // true
     searchParams.get("topic") === "api"; // true
     searchParams.getAll("topic"); // ["api"]
     searchParams.get("foo") === null; // true
     searchParams.append("topic", "webdev");
     searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
     searchParams.set("topic", "More webdev");
     searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
     searchParams.delete("topic");
     searchParams.toString(); // "q=URLUtils.searchParams"
    
    
    [1]: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
    
    0 讨论(0)
  • 2020-11-29 22:22

    From DimitriDushkin on GitHub:

    import { browserHistory } from 'react-router';
    
    /**
     * @param {Object} query
     */
    export const addQuery = (query) => {
      const location = Object.assign({}, browserHistory.getCurrentLocation());
    
      Object.assign(location.query, query);
      // or simple replace location.query if you want to completely change params
    
      browserHistory.push(location);
    };
    
    /**
     * @param {...String} queryNames
     */
    export const removeQuery = (...queryNames) => {
      const location = Object.assign({}, browserHistory.getCurrentLocation());
      queryNames.forEach(q => delete location.query[q]);
      browserHistory.push(location);
    };
    

    or

    import { withRouter } from 'react-router';
    import { addQuery, removeQuery } from '../../utils/utils-router';
    
    function SomeComponent({ location }) {
      return <div style={{ backgroundColor: location.query.paintRed ? '#f00' : '#fff' }}>
        <button onClick={ () => addQuery({ paintRed: 1 })}>Paint red</button>
        <button onClick={ () => removeQuery('paintRed')}>Paint white</button>
      </div>;
    }
    
    export default withRouter(SomeComponent);
    
    0 讨论(0)
  • 2020-11-29 22:23

    John's answer is correct. When I'm dealing with params I also need URLSearchParams interface:

    this.props.history.push({
        pathname: '/client',
        search: "?" + new URLSearchParams({clientId: clientId}).toString()
    })
    

    You might also need to wrap your component with a withRouter HOC eg. export default withRouter(YourComponent);.

    0 讨论(0)
  • 2020-11-29 22:30

    I prefer you to use below function that is ES6 style:

    getQueryStringParams = query => {
        return query
            ? (/^[?#]/.test(query) ? query.slice(1) : query)
                .split('&')
                .reduce((params, param) => {
                        let [key, value] = param.split('=');
                        params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
                        return params;
                    }, {}
                )
            : {}
    };
    
    0 讨论(0)
提交回复
热议问题