Back to Hooks

useCookieState

packages/hooks/src/useCookieState/index.zh-CN.md

3.9.72.7 KB
Original Source

useCookieState

一个可以将状态存储在 Cookie 中的 Hook 。

代码演示

<code src="./demo/demo1.tsx" />

setState 可以接收函数

<code src="./demo/demo2.tsx" /> <code src="./demo/demo3.tsx" />

API

typescript
type State = string | undefined;

type SetState = (
  newValue?: State | ((prevState?: State) => State),
  options?: Cookies.CookieAttributes,
) => void;

const [state, setState]: [State, SetState] = useCookieState(
  cookieKey: string,
  options?: Options,
);

注意:如果想从 document.cookie 中删除这条数据,可以使用 setState()setState(undefined)

Params

参数说明类型默认值
cookieKeyCookie 的 key 值string-
options可选项,配置 Cookie 属性Options-

Result

参数说明类型
state本地 Cookie 值string | undefined
setState设置 Cookie 值SetState

setState 可以更新 cookie options,会与 useCookieState 设置的 options 进行 merge 操作。

const targetOptions = { ...options, ...updateOptions }

Options

参数说明类型默认值
defaultValue可选,定义 Cookie 默认值,但不同步到本地 Cookiestring | undefined | (() => (string | undefined))undefined
expires可选,定义 Cookie 存储有效时间number | Date-
path可选,定义 Cookie 可用的路径string/
domain可选,定义 Cookie 可用的域,默认为 Cookie 创建的域名string-
secure可选,Cookie 传输是否需要 https 安全协议booleanfalse
sameSite可选,Cookie 不能与跨域请求一起发送strict | lax | none-

Options 与 js-cookie attributes 保持一致。