持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第21天,点击查看活动详情
今天开始一起学习分享 ahooks 的源码
ahooks是阿里巴巴出品的一套高质量可靠的 React Hooks 库
今天分享 第16个 hooks-useCookieState
useCookieState
首先看下useCookieState 的作用是什么
useCookieState 的作用是 一个可以将状态存储在 Cookie 中的 Hook 。
接下来 看下 API
API
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,
);
Params
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
cookieKey | Cookie 的 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 默认值,但不同步到本地 Cookie | string | undefined | (() => (string | undefined)) | undefined |
expires | 可选,定义 Cookie 存储有效时间 | number | Date | - |
path | 可选,定义 Cookie 可用的路径 | string | / |
domain | 可选,定义 Cookie 可用的域,默认为 Cookie 创建的域名 | string | - |
secure | 可选,Cookie 传输是否需要 https 安全协议 | boolean | false |
sameSite | 可选,Cookie 不能与跨域请求一起发送 | strict | lax | none | - |
Options 与 js-cookie attributes 保持一致。
接下来 看下 用法
将 state 存储在 Cookie 中
刷新页面后,可以看到输入框中的内容被从 Cookie 中恢复了。
import React from 'react';
import { useCookieState } from 'ahooks';
export default () => {
const [message, setMessage] = useCookieState('useCookieStateString');
return (
<input
value={message}
placeholder="Please enter some words..."
onChange={(e) => setMessage(e.target.value)}
style={{ width: 300 }}
/>
);
};
接下来一起看下 源码
源码
1.首先定义传入参数的类型
export interface Options extends Cookies.CookieAttributes {
defaultValue?: State | (() => State);
}
cookieKey: string, options: Options = {}
2.定义初始值,这个初始值有个逻辑,首先去cookie中根据key获取值,如果是字符串,则直接返回,如果不是则是返回对象中的value
const [state, setState] = useState<State>(() => {
const cookieValue = Cookies.get(cookieKey);
if (isString(cookieValue)) return cookieValue;
if (isFunction(options.defaultValue)) {
return options.defaultValue();
}
return options.defaultValue;
});
3.接着编写更新state函数,根据options获取默认值,然后使用setState方法更新值
const updateState = useMemoizedFn(
(
newValue: State | ((prevState: State) => State),
newOptions: Cookies.CookieAttributes = {},
) => {
const { defaultValue, ...restOptions } = { ...options, ...newOptions };
setState((prevState) => {
const value = isFunction(newValue) ? newValue(prevState) : newValue;
if (value === undefined) {
Cookies.remove(cookieKey);
} else {
Cookies.set(cookieKey, value, restOptions);
}
return value;
});
},
);
4.最后返回state和updateState方法
return [state, updateState] as const;