如何从当前路由中删除查询参数?

IT技术 reactjs react-router history.js
2021-05-17 09:34:05

我有一条/cart路线,它接受几个名为validateand的查询参数email它们仅在用户未登录时使用,并且在用户登录时是不必要的。在后一种情况下,我想从 URL 中删除它们。

这是我当前onEnter/cart路线功能

const requireCartLogin = (props, replace) => {
    const { email, validate } = props.location.query;

    // Exit process if the 'validate' query isn’t present.
    if (typeof validate === 'undefined') { return; }

    if (!isAuthenticated() || requiresReauthentication()) {
        replace({
            pathname: '/account/signin',
            query: { step: 'signin' },
            state: {
                email: typeof email !== 'undefined' ? email : null,
                auth: true,
                next: '/cart'
            }
        });
    } else if (isAuthenticated()) {
        replace({
            pathname: '/cart',
            query: null
        });
    }
};

这是条件的第二部分应该删除查询参数,但它目前不起作用。我在这里错过了什么?

4个回答

看看 Dimitry Dushin 的例子

创建 2 个实用函数,如下所示:

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);
};

并使用它来操作查询,如下所示:

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);

请注意,这在 .v4 的 >v4 中不起作用react-router

我搜索了一段时间关于如何执行此操作并最终意识到我需要做的只是像往常一样使用历史记录推送到 url(没有参数):

// this piece of code is in /app/settings/account
React.useEffect(() => {

        let params = queryString.parse(location.search)
        if (params && params.code) {
            doSomething(params.code)                                                            
            history.push('/app/settings/account')           
        }
    
}, [])

假设 react-router-dom

删除是最棘手的部分,因此首先您需要能够以合理的格式获取当前参数。

您可以通过useLocation钩子以字符串形式获取搜索参数

但是使用这样的字符串令人困惑,我更喜欢处理一个对象。

例如?filter=123&filter=something&page=1将产生以下对象。

{
    filter: ['123', 'something'],
    page: ['1']
}

更容易操纵。

所以我们应该创建 2 个实用函数,一个将搜索字符串转换为上述对象,另一个将对象转换回搜索字符串。

toParamObject.js

const toParamObject = (queryString) => {
  const params = new URLSearchParams(queryString);
  let paramObject = {};
  params.forEach((value, key) => {
    if (paramObject[key]) {
      paramObject = {
        ...paramObject,
        [key]: [
          ...paramObject[key],
          value,
        ],
      };
    } else {
      paramObject = {
        ...paramObject,
        [key]: [value],
      };
    }
  });

  return paramObject;
};

toQueryString.js

const toQueryString = (paramObject) => {
  let queryString = '';
  Object.entries(paramObject).forEach(([paramKey, paramValue]) => {
    if (paramValue.length === 0) {
      return;
    }
    queryString += '?';
    paramValue.forEach((value, index) => {
      if (index > 0) {
        queryString += '&';
      }
      queryString += `${paramKey}=${value}`;
    });
  });

  // This is kind of hacky, but if we push '' as the route, we lose 
  // our page, and base path etc.
  // So instead.. pushing a '?' just removes all the current query strings
  return queryString !== '' ? queryString : '?';
};

得到

// search is from useLocation, and we can just pass in the name of the param we want
const get = (key) => toParamObject(search)[key] || [];

消除

const remove = (key, value) => {
    // First get the current params get()
    const thisParam = get(param).filter((val) => val !== value);
    const newParamObject = {
      ...toParamObject(search), // from useLocation
      [param]: thisParam,
    };
    push(`${toQueryString(newParamObject)}`); // from useHistory
};

您可以简单地覆盖搜索参数,history.push如下所示:

history.push({
    pathname: 'what/ever/your/path/is',
    search: '',
});