基本用法
用 useQueryState 替换 React.useState
先决条件
你是否已使用适当的适配器设置你的应用?如果是,则一切就绪!
如果你正在使用 React.useState 来管理本地 UI 状态,
你可以将其替换为 useQueryState 来与 URL 同步。
'use client'
import { useQueryState } from 'nuqs'
export function Demo() {
const [name, setName] = useQueryState('name')
return (
<>
<input value={name || ''} onChange={e => setName(e.target.value)} />
<button onClick={() => setName(null)}>Clear</button>
<p>Hello, {name || 'anonymous visitor'}!</p>
</>
)
}useQueryState 接受一个必需参数:在查询字符串中使用的键。
类似于 React.useState,它返回一个数组,其中包含查询字符串中的字符串值(如果未找到则为 null),以及一个状态更新函数。
我们的演示示例的输出示例:
| URL | name 值 | 备注 |
|---|---|---|
/ | null | URL 中没有 name 键 |
/?name= | '' | 空字符串 |
/?name=foo | 'foo' | |
/?name=2 | '2' | 默认始终返回字符串,请参阅 解析器 |
提示
将值设置为 null 将从查询字符串中移除该键。
默认值
当 URL 中不存在查询字符串时,默认行为是返回 null 作为状态。
这可能会使状态更新和 UI 渲染变得繁琐。 以这个简单的计数器示例为例,它存储在 URL 中:
import { useQueryState, parseAsInteger } from 'nuqs'
export default () => {
const [count, setCount] = useQueryState('count', parseAsInteger)
return (
<>
<pre>count: {count}</pre>
<button onClick={() => setCount(0)}>Reset</button>
{/* 处理 setCount 中的 null 值很烦人: */}
<button onClick={() => setCount(c => (c ?? 0) + 1)}>+</button>
<button onClick={() => setCount(c => (c ?? 0) - 1)}>-</button>
<button onClick={() => setCount(null)}>Clear</button>
</>
)
}你可以将默认值作为 useQueryState 的第二个参数提供(或通过解析器上的 .withDefault 构建器方法):
const [search] = useQueryState('search', { defaultValue: '' })
// ^? string
const [count] = useQueryState('count', parseAsInteger)
// ^? number | null -> 无默认值 = 可为空
const [count] = useQueryState('count', parseAsInteger.withDefault(0))
// ^? number这使得处理状态更新变得更加容易:
const increment = () => setCount(c => c + 1) // c 永远不会是 null
const decrement = () => setCount(c => c - 1) // c 永远不会是 null
const clearCount = () => setCount(null) // 从 URL 中移除查询注意
默认值是 React 内部的,它不会写入 URL 除非你显式设置它 并使用 clearOnDefault: false 选项。
提示
如果解析器的值是_无效_的,则也会返回默认值。
提示
当指定了默认值时,将状态设置为 null:
- 从 URL 中清除查询
- 将默认值返回作为状态