简体   繁体   English

如何在 Next.js 中使用查询参数?

[英]How to use query params in Next.js?

In my Next.js API functions like:在我的 Next.js API 函数中,例如:

export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
  const { someQueryParam } = req.query;
  doSomething(someQueryParam);
  ...

I see TypeScript error:我看到 TypeScript 错误:

Argument of type 'string | 'string | 类型的参数string[]' is not assignable to parameter of type 'string'. string[]' 不能分配给“string”类型的参数。 Type 'string[]' is not assignable to type 'string'.ts(2345)类型 'string[]' 不可分配给类型 'string'.ts(2345)

So I've started using this helper function I wrote:所以我开始使用我写的这个辅助函数:

export function getSimpleStringFromParam(paramValue: string | string[] | undefined) {
  if (paramValue) {
    return typeof paramValue === 'string' ? paramValue : paramValue[0];
  } else {
    return '';
  }
}

It works fine, but it feels ugly and weird and feels like what I'm trying to do would be such a common need that Next.js or Node would handle it more smoothly.它工作正常,但感觉丑陋和怪异,感觉就像我正在尝试做的事情是如此普遍的需求,以至于 Next.js 或 Node 会更顺利地处理它。 So I feel like I'm misunderstanding something.所以我觉得我误会了什么。

Is there a more official / better way to pluck simple string values out of the query params?有没有更官方/更好的方法从查询参数中提取简单的字符串值?

I look at your helper function and see that someQueryParam is string我查看了您的辅助函数,发现someQueryParam是字符串

export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
  const someQueryParam: string = req.query.someQueryParam
    ? req.query.someQueryParam as string
    : "";
  doSomething(someQueryParam);
}

But if you need get string | string[]但是如果你需要获取string | string[] string | string[] use that: string | string[]使用它:

export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
  const someQueryParam: string | string[] = req.query.someQueryParam
    ? req.query.someQueryParam
    : "";
  doSomething(someQueryParam);
}

OR或者

 export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
  const { someQueryParam } = req.query.someQueryParam
    ? req.query
    : { someQueryParam: "" };
  doSomething(someQueryParam);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM