- Published on
alibaba/hooks代码解读之useCookieState
- Authors
- Name
- 祝你好运
useCookieState
是用来管理Cookie的,可以用hook的方式十分方便的来访问Cookie。
useCookieState
简介
首先要明白什么是Cookie,可以看下MDN上面的定义,Cookie和Document.cookie。我们可以看出Cookie本身就是一个在HTTP请求头中的字段,我们可以通过document.cookie
来存取,但是存取的时候它是一个字符串,需要转化为key-value的形式,而且会牵涉到编码/解码,所以不建议裸写存取方法。而useCookieState
也是用的js-cookie来做的,这个hook本身就是一个以hook形式来访问Cookie。
总体结构
代码的整体结构很简单,一句话就是useState
,其中useState
的默认值是一个函数,这个用法官网上面也有介绍:Lazy initial state。另外就是状态的更新是被updateState
封装起来了,而且updateState
用了useCallback
来保证当参数不变的时候不会变。
关键代码
这里看懂总体结构之后,就基本没有问题了,除了上面提到的初始值的懒加载,还有就是我在alibaba/hooks代码解读之useBoolean和useToggle里面提到的Functional updates。最后一点就是useCookieState
的更新函数可以通过设置null
或者undefined
来清除某个Cookie。
CookieAttributes
最后这个Cookie.CookieAttributes
的代码我在GitHub上面没有找到,所以就通过在node_modules
里面找到的@types/js-cookie
里面的代码,贴到这里:
interface CookieAttributes {
/**
* Define when the cookie will be removed. Value can be a Number
* which will be interpreted as days from time of creation or a
* Date instance. If omitted, the cookie becomes a session cookie.
*/
expires?: number | Date | undefined;
/**
* Define the path where the cookie is available. Defaults to '/'
*/
path?: string | undefined;
/**
* Define the domain where the cookie is available. Defaults to
* the domain of the page where the cookie was created.
*/
domain?: string | undefined;
/**
* A Boolean indicating if the cookie transmission requires a
* secure protocol (https). Defaults to false.
*/
secure?: boolean | undefined;
/**
* Asserts that a cookie must not be sent with cross-origin requests,
* providing some protection against cross-site request forgery
* attacks (CSRF)
*/
sameSite?: 'strict' | 'Strict' | 'lax' | 'Lax' | 'none' | 'None' | undefined;
/**
* An attribute which will be serialized, conformably to RFC 6265
* section 5.2.
*/
[property: string]: any;
}