【问题标题】:Create url with query params in Next.js在 Next.js 中使用查询参数创建 url
【发布时间】:2021-10-04 21:58:48
【问题描述】:

我想通过以下方式从查询参数创建一个 url:

 router.push(
      {
        pathname: '/cars',
        query: colors + type + price,

      },
      undefined,
      {
        shallow: true,
      },
  );

const colors = ['red', 'blue', 'yellow']; //the arrays could contain many others values
const type = ['offroad', 'sport'];
const price = 'hight'  //this is a string

我想实现,当我点击触发router.push的按钮时,下一个: /cars?color=red,yellow,blue&type=offroad,sport&price=hight

【问题讨论】:

  • 如果你有多个值的相同键,你将如何获得查询?
  • @Shyam,你是什么意思?
  • 如果您的查询为 color=red&color=blue,您将如何解析它们?我建议您使用这种格式/cars?colors=red,blue,green&type=sports
  • @Shyam,我明白你的意思,但我需要针对上述情况的解决方案。你能帮忙吗?
  • 查询参数必须是有效对象。在您的情况下,您有多个值的相同键,这将被覆盖。

标签: reactjs next.js


【解决方案1】:

你可以这样做:

 const router = useRouter();
 router.push(
  {
    pathname: '/cars',
    query: {
      colors,
      type,
      price,
  },
  undefined,
  {
    shallow: true,
  },

);

根据 Next/Router 类型查询 typeof ParsedUrlQuery 相当于

interface ParsedUrlQuery extends NodeJS.Dict<string | string[]> { }

也就是说,next/router 既可以解析字符串也可以解析字符串数组

【讨论】:

【解决方案2】:

https://nextjs.org/docs/api-reference/next/router#with-url-object

你试试这个

router.push({
          pathname: '/cars',
          query: {
              colors: colors.join(","),
               types: types.join(",")
           },
 }) 

【讨论】:

  • 请解释一下?
  • router.push 将您的查询对象解析为查询字符串。所以它会从`{colors:red,blue,type:sports}`转换为colors=red, blue&amp;type=sports
  • @Shyam,但是如何获得 /cars?color=red&color=yellow&color=blue&type=offroad&type=sport&price=hight?
【解决方案3】:

如果您有一个动态路由并希望能够普遍使用它,例如,每个页面上的某些链接(在标题中)您可以通过提供所有当前可用的路由参数并添加或替换附加或替换来实现此目的现有的。

// ...
const router = useRouter();
// ...

<Link
    href={{
        pathname: router.pathname,
        query: { ...router.query, colors, type, price },
    }}
    passHref
    shallow
    replace
></Link>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 2010-10-17
    相关资源
    最近更新 更多