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> ); }
結果
點擊按鈕以更新或清除 cookie
cookie:default-value
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