useCookie
有助于在 CookieStore 中存储、更新和删除值的 hook
备注
当你在多个组件中使用相同键的 useCookie hook 并使用 setCookieValue 时,它不会触发其他使用此 hook 的组件进行更新。
如果你想要一个广播效果,可以参考以下链接:https://github.com/childrentime/reactuse/issues/91
Usage
实时编辑器
function Demo() { const defaultOption = { path: "/", }; const cookieName = "cookie-key"; const [cookieValue, updateCookie, refreshCookie] = useCookie( cookieName, defaultOption, "default-value", ); const updateButtonClick = () => { updateCookie("new-cookie-value"); }; const deleteButtonClick = () => { updateCookie(undefined); }; const change = () => { if ("cookieStore" in window) { const store = window.cookieStore as any; store.set({ name: cookieName, value: "changed" }); } else { document.cookie = `${cookieName}=changed; path=/`; } }; return ( <div> <p>点击按钮来更新或清除cookie</p> <p color="blue">cookie: {cookieValue || "无值"}</p> <button onClick={updateButtonClick}>更新cookie</button> <button onClick={deleteButtonClick}>清除cookie</button> <button onClick={change}> 通过其他方法更改cookie </button> <button onClick={refreshCookie}>刷新cookie</button> </div> ); }
结果
Loading...
API
useCookie
Returns
readonly [UseCookieState, (newValue: UseCookieState | ((prevState: UseCookieState) => UseCookieState)) => void, () => void]: 包含以下元素的元组:
- cookie 的当前值。
- 更新 cookie 值的函数。
- 刷新 cookie 值的函数,以防其他事件更改它。
Arguments
| 参数名 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| key | 键值 | string (必填) | - |
| options | 透传给 js-cookie 的参数 | any | - |
| defaultValue | 默认值,ssr必须传递 | string | undefined | - |
useCookieState
Type
export type UseCookieState = string | undefined