reactjs - 在 Next.js 中替换查询中的值

我正在使用 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,
      },
    );

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

最佳答案

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

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

https://stackoverflow.com/questions/64636739/

相关文章:

python - 为什么我的 Django 表单不是 "valid"?无法获取更新数据库的 POST

jsf - 用作 JSF 值的 Java 记录

java - 给定算法的时间复杂度是多少?

python - 如何将文件夹从 AzureML 笔记本文件夹下载到本地或 Blob 存储?

android - 如何在 ionic +react + capacitor 项目中设置最低 and

r - 如何在 R Shiny 应用程序中对齐 downloadButton 和 ActionBut

python - 是否可以设置 lint 自定义设置并忽略 pylance

curl - Google Cloud Storage - 使用 CURL 请求下载文件

python - 使用 boto3 获取新创建的亚马逊 ec2 实例的公共(public) IPv4

kubernetes - 如何在我的 configmap.yaml (Helm) 中使用 json