Change URL parameters

前端 未结 26 2448
孤独总比滥情好
孤独总比滥情好 2020-11-22 08:40

I have this URL:

site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc

what I need is to be able to

26条回答
  •  执笔经年
    2020-11-22 09:16

    Here is a simple solution using the query-string library.

    const qs = require('query-string')
    function addQuery(key, value) {
      const q = qs.parse(location.search)
      const url = qs.stringifyUrl(
        {
          url: location.pathname,
          query: {
          ...q,
          [key]: value,
          },
        },
        { skipEmptyString: true }
      );
      window.location.href = url
      // if you are using Turbolinks
      // add this: Turbolinks.visit(url)
    }
    // Usage
    addQuery('page', 2)
    

    If you are using react without react-router

    export function useAddQuery() {
      const location = window.location;
      const addQuery = useCallback(
        (key, value) => {
          const q = qs.parse(location.search);
          const url = qs.stringifyUrl(
            {
              url: location.pathname,
              query: {
                ...q,
                [key]: value,
              },
            },
            { skipEmptyString: true }
          );
          window.location.href = url
        },
        [location]
      );
    
      return { addQuery };
    }
    // Usage
    const { addQuery } = useAddQuery()
    addQuery('page', 2)
    

    If you are using react with react-router

    export function useAddQuery() {
      const location = useLocation();
      const history = useHistory();
    
      const addQuery = useCallback(
        (key, value) => {
          let pathname = location.pathname;
          let searchParams = new URLSearchParams(location.search);
          searchParams.set(key, value);
          history.push({
            pathname: pathname,
            search: searchParams.toString()
          });
        },
        [location, history]
      );
    
      return { addQuery };
    }
    
    // Usage
    const { addQuery } = useAddQuery()
    addQuery('page', 2)
    

    PS: qs is the import from query-string module.

提交回复
热议问题