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

后端 未结 8 2046
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: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 
    ; } export default withRouter(SomeComponent);

提交回复
热议问题