【问题标题】:Replace a value in query in Next.js在 Next.js 中替换查询中的值
【发布时间】:2021-02-14 14:09:37
【问题描述】:

我正在使用 Next js。我使用查询参数创建 url: http://localhost:3000/cars?colors=red&nr=20。当我单击按钮时,是否有可能仅更改 URL 的特定部分,例如:http://localhost:3000/cars?colors=blue&nr=20。所以在这种情况下,我只是将颜色更改为蓝色。 我用过:

  router.replace(
      {
        pathname: '/...',
        query:  {
          color: blue
        },
      },
      undefined,
      {
        shallow: true,
      },
    );

但它不起作用。
如何解决这个问题?

【问题讨论】:

  • 你的意思是它不工作?浏览器没有更新网址?还是你的 UI 颜色没有改变?
  • @SabrinaLuo,浏览器更新它,但我丢失了另一部分 url:http://localhost:3000/cars?colors=blue。您可以看到 &nr=20 丢失了,我只需要替换 url 的特定部分,但我不想更改的项目保持不变。你有解决办法吗?

标签: reactjs next.js


【解决方案1】:

您需要将所有查询添加到您的router.replace query,例如

  router.replace(
  {
    pathname: '/...',
    query:  {
      nr:20,
      color: blue
    },
  },
  undefined,
  {
    shallow: true,
  },
);

为了更简单,你可以这样做

  router.replace(
  {
    pathname: '/...',
    query:  {
      ...router.query, // list all the queries here
      color: blue // override the color property
    },
  },
  undefined,
  {
    shallow: true,
  },
);
猜你喜欢
  • 1970-01-01
  • 2010-12-27
  • 1970-01-01
  • 2016-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-08
  • 2013-09-25
相关资源
最近更新 更多