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>Click on the button to update or clear the cookie</p> <p color="blue">cookie: {cookieValue || "no value"}</p> <button onClick={updateButtonClick}>Update the cookie</button> <button onClick={deleteButtonClick}>Clear the cookie</button> <button onClick={change}> Changing the cookie through other methods </button> <button onClick={refreshCookie}>Refresh the 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