在 Next.js 中使用查询参数创建 url

Ask*_*ing 8 reactjs next.js

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

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

      },
      undefined,
      {
        shallow: true,
      },
  );
Run Code Online (Sandbox Code Playgroud)

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

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

Sab*_*Luo 11

你可以简单地做:

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

);

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

interface ParsedUrlQuery extends NodeJS.Dict<string | string[]> { }
Run Code Online (Sandbox Code Playgroud)

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


FDi*_*isk 5

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

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

<Link
    href={{
        pathname: router.pathname,
        query: { ...router.query, colors, type, price },
    }}
    passHref
    shallow
    replace
></Link>
Run Code Online (Sandbox Code Playgroud)