NEXT JS - 如何删除查询参数

NEXT JS - How to remove Query Params

如何在不刷新 Next JS (React) 页面的情况下删除或更新查询参数?

  1. 用户在 URL /about?login=success&something=yes
  2. 单击一个按钮并在不刷新页面的情况下从 URL 中删除 ?login=success&something=yes。点击按钮后的URL会变成/about

如何实现?

如本 中所述,我知道可以使用 Router 删除查询参数或查询字符串。但是,useLocationuseHistorynext/router 上不可用。

Nextjs 有 useRouter 挂钩,可用于以编程方式更改 url。 Link to the docs.

根据 History,您可以使用 history.replaceState 来实现它。

window.history.replaceState(null, '', '/about')

您可以使用 next/router 删除或更新 URL 中的查询参数。

const router = useRouter();

router.replace('/about', undefined, { shallow: true });

使用 replace 防止在历史记录中添加新的 URL 条目(否则只需使用 push),并且 shallow: true 允许您 change the URL without running data fetching methods .这将导致重新呈现,但不会刷新页面本身。

我对我的类似问题的解决方案是这样的:

push(`${asPath.split('?')[0]}?comp=${id}`);

或者如果你想拥有可重复使用的功能:


function delQuery(asPath) {
  return asPath.split('?')[0]
}

...
const {push, asPath} = useRouter()

push(`${delQuery(asPath)}?comp=${id}`);

如果您想从查询中删除单个或多个参数,

const router = useRouter();

/**
 * If removeList is empty, the function removes all params from url.
 * @param {*} router 
 * @param {*} removeList 
 */
const removeQueryParamsFromRouter = (router, removeList = []) => {
    if (removeList.length > 0) {
        removeList.forEach((param) => delete router.query[param]);
    } else {
        // Remove all
        Object.keys(object).forEach((param) => delete object[param]);
    }
    router.replace(
        {
            pathname: router.pathname,
            query: router.query
        },
        undefined,
        /**
         * Do not refresh the page
         */
        { shallow: true }
    );
};

const anyFunction = () => {
    // "/about?firstParam=5&secondParam=10"
    removeQueryParamsFromRouter(router, ['myParam']);
    // "/about?secondParam=10"
};

您可以通过 []:

从路由器对象中删除查询参数
const router = useRouter();
router.query.something = [];
import {NextRouter} from 'next/router'

export const removeQueryParams = (
  router: NextRouter,
  paramsToRemove: Array<string> = []
) => {
  if (paramsToRemove.length > 0) {
    paramsToRemove.forEach((param) => delete router.query[param])
  } else {
    // Remove all query parameters
    Object.keys(router.query).forEach((param) => delete router.query[param])
  }
  router.replace(
    {
      pathname: router.pathname,
      query: router.query,
    },
    undefined,
    /**
     * Do not refresh the page when the query params are removed
     */
    {shallow: true}
  )
}
const anyFunction = () => {
    // "/about?firstParam=5&secondParam=10"
    removeQueryParamsFromRouter(router, ['myParam']);
    // "/about?secondParam=10"
};

这里提到的原始答案由于对象未定义而引发错误,而且它是它的打字稿版本。

您可以简单地使用“router.push”或“router.replace”和“shallow: true", 这将在不重新加载页面的情况下删除查询参数。

const router = useRouter();
router.replace('/about', undefined, { shallow: true });

或者,如果您想删除单个查询,那么这种快速简便的方法将对您有所帮助

eg. /about?login=success&something=yes

const router = useRouter();
// perform this inside function call or button click etc
delete router.query.something;
router.push(router)

现在更新的路线将是

/about?login=success