【问题标题】:NEXT JS - How to remove Query Params?NEXT JS - 如何删除查询参数?
【发布时间】:2021-04-12 20:39:35
【问题描述】:

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

  1. 用户在 URL /about?login=success&something=yes
  2. 单击一个按钮并从 URL 中删除 ?login=success&something=yes 而不刷新页面。点击按钮后的网址为/about

我怎样才能实现它?

正如thread 中提到的,我知道可以使用路由器删除查询参数或查询字符串。但是,useLocationuseHistorynext/router 上不可用。

【问题讨论】:

  • window.history.replaceState 对你有用吗?我也试过了,但是当查询参数存在时,next.js 会强制 url 恢复

标签: reactjs next.js next-router


【解决方案1】:

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

【讨论】:

  • 是的,我知道 useRouter ? 但是我应该更改哪个值?以及如何?
【解决方案2】:

根据History,你可以使用history.replaceState来实现这个。

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

【讨论】:

  • 是的,这个解决方案有效。谢谢,我也加if (typeof window !== "undefined") { window.history.replaceState(null, '', '/about') }
  • 我尝试了这个解决方案,url更改被还原
  • 此解决方案有效,但后退按钮出现问题。
  • 抱歉,但这不是我推荐的解决方案
  • 我推荐给你,使用 useRouter : router.replace('/about', undefined, { shallow: true })
【解决方案3】:

您可以使用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。这将导致重新渲染,但不会刷新页面本身。

【讨论】:

  • 我之前试过这个解决方案,但是它触发了页面刷新?
【解决方案4】:

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

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

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


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

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

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

【讨论】:

    【解决方案5】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-02-09
      • 2016-02-29
      • 1970-01-01
      • 2023-01-09
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      • 2021-10-22
      • 2018-07-11
      相关资源
      最近更新 更多