useUrlSearchParams

Tags:

一个 React 钩子(Hook),用于管理 URL 的搜索参数。

useUrlSearchParams 有三种模式:

  • history:如 /path/to/page?a=1&b=2
  • hash:如 /path/to/page#heading?a=1&b=2 (在 hash 中包含 ?
  • hash-params:如 /path/to/page#/a=1&b=2 (在 hash 中不包含 ?

演示

源码
Params (history):
{"mode":"mode","val":["val"]}
Params (hash):
{}
Params (hash-params):
{}

用法

请查看 API。

源码

点击下方链接跳转 GitHub 查看源代码。

API

const [usp, setUsp, clearUsp] = useUrlSearchParams(mode, options)

模式 Mode

export type UseUrlSearchParamsMode = 'history' | 'hash' | 'hash-params'

选项 Options

export interface UseUrlSearchParamsOptions<T> { /** * 从 URLSearchParams 中移除空值 * * @defaultValue true */ removeNullishValues?: boolean /** * 从 URLSearchParams 中移除假值 * * @defaultValue false */ removeFalsyValues?: boolean /** * URLSearchParams 的初始值 * * @defaultValue {} */ initialValue?: T & Record<any, any> /** * 自动写回 `window.history` * * @defaultValue true */ write?: boolean }

返回值

export type UseUrlSearchParamsReturns<T extends Record<string, any>> = [T, UseSetStateSetMergedState<T>, Noop]