实用工具

用于处理查询字符串的实用工具

序列化器助手

Introduced in version 1.16.0.

要使用状态值填充 <Link> 组件,您可以使用 createSerializer 助手。

将描述搜索参数的对象传递给它,它将返回一个函数,该函数接受值并生成由钩子序列化的查询字符串。

示例:

import {
  createSerializer,
  parseAsInteger,
  parseAsIsoDateTime,
  parseAsString,
  parseAsStringLiteral
} from 'nuqs/server' // can also be imported from 'nuqs' in client code

const searchParams = {
  search: parseAsString,
  limit: parseAsInteger,
  from: parseAsIsoDateTime,
  to: parseAsIsoDateTime,
  sortBy: parseAsStringLiteral(['asc', 'desc'])
}

// Create a serializer function by passing the description of the search params to accept
const serialize = createSerializer(searchParams)

// Then later, pass it some values (a subset) and render them to a query string
serialize({
  search: 'foo bar',
  limit: 10,
  from: new Date('2024-01-01'),
  // here, we omit `to`, which won't be added
  sortBy: null // null values are also not rendered
})
// ?search=foo+bar&limit=10&from=2024-01-01T00:00:00.000Z

基础参数

返回的 serialize 函数可以接受一个基础参数,在其上追加/修改搜索参数:

serialize('/path?baz=qux', { foo: 'bar' }) // /path?baz=qux&foo=bar

const search = new URLSearchParams('?baz=qux')
serialize(search, { foo: 'bar' }) // ?baz=qux&foo=bar

const url = new URL('https://example.com/path?baz=qux')
serialize(url, { foo: 'bar' }) // https://example.com/path?baz=qux&foo=bar

// Passing null removes existing values
serialize('?remove=me', { foo: 'bar', remove: null }) // ?foo=bar

更短的搜索参数键

就像在 useQueryStates 中一样,您可以定义一个 urlKeys 对象,将由解析器定义的变量名映射到 URL 中的更短键:

const serialize = createSerializer(
  {
    // 1. Use variable names that make sense for your domain/business logic
    latitude: parseAsFloat,
    longitude: parseAsFloat,
    zoomLevel: parseAsInteger
  },
  {
    // 2. Remap them to shorter keys in the URL
    urlKeys: {
      latitude: 'lat',
      longitude: 'lng',
      zoomLevel: 'z'
    }
  }
)

// 3. Use your variable names when calling the serializer,
// and the shorter keys will be rendered in the URL:
serialize({
  latitude: 45.18,
  longitude: 5.72,
  zoomLevel: 12
})
// ?lat=45.18&lng=5.72&z=12

处理 URLSearchParams

Introduced in version 2.6.0.

就像在 <NuqsAdapter> 中一样,您可以指定一个 processUrlSearchParams 函数,在序列化之前修改搜索参数。

例如,通过按字母顺序排序搜索参数键,这对于一致的规范 URL(用于 SEO)很有用:

const serialize = createSerializer(
  {
    a: parseAsInteger,
    z: parseAsInteger
  },
  {
    processUrlSearchParams: (search) => {
      // Note: you can modify search in-place,
      // or return a copy, as you wish.
      search.sort()
      return search
    }
  }
)

serialize('?foo=bar', {
  a: 1,
  z: 1
})
// ?a=1&foo=bar&z=1
// merged, then sorted

解析器类型推断

Introduced in version 1.18.0.

要访问解析器返回的底层类型,您可以使用 inferParserType 类型助手:

import { parseAsInteger, type inferParserType } from 'nuqs' // or 'nuqs/server'

const intNullable = parseAsInteger
const intNonNull = parseAsInteger.withDefault(0)

inferParserType<typeof intNullable> // number | null
inferParserType<typeof intNonNull> // number

对于描述解析器的对象(您会将其传递给 createLoaderuseQueryStates),inferParserType 将返回对象类型,其中解析器被替换为其推断类型:

import {
  parseAsBoolean,
  parseAsInteger,
  type inferParserType
} from 'nuqs' // or 'nuqs/server'

const parsers = {
  a: parseAsInteger,
  b: parseAsBoolean.withDefault(false)
}

inferParserType<typeof parsers>
// { a: number | null, b: boolean }

标准 Schema

Introduced in version 2.5.0.

搜索参数定义可以转换为 Standard Schema,用于验证外部源并将类型推断传递给其他工具。

import {
  createStandardSchemaV1,
  parseAsInteger,
  parseAsString,
} from 'nuqs' // or 'nuqs/server'

// 1. Define your search params as usual
export const searchParams = {
  searchTerm: parseAsString.withDefault(''),
  maxResults: parseAsInteger.withDefault(10)
}

// 2. Then create a Standard Schema compatible validator
export const validateSearchParams = createStandardSchemaV1(searchParams)

// 3. Use it with other tools, like tRPC:
router({
  search: publicProcedure.input(validateSearchParams).query(...)
})

TanStack Router & validateSearch

您可以将标准 schema 验证器传递给 TanStack RoutervalidateSearch,以实现类型安全的 nuqs URL 状态链接,但为了保持这些值可选(因为 nuqs 使用与 TSR 不同的默认策略),您需要将输出标记为 Partial,使用 partialOutput 选项:

src/routes/search.tsx
import { createStandardSchemaV1 } from 'nuqs'

const validateSearch = createStandardSchemaV1(searchParams, {
  partialOutput: true
})

export const Route = createFileRoute('/search')({
  validateSearch
})

注意

TanStack Router 支持仍处于实验阶段,并带有注意事项, 请参阅 适配器文档 以获取更多关于支持内容的信息。