History
jotai-history 是一个用于追踪 Jotai 状态历史的工具包。
npm install jotai-historywithHistory
Section titled “withHistory”import { withHistory } from 'jotai-history'
const targetAtom = atom(0)const limit = 2const historyAtom = withHistory(targetAtom, limit)
function Component() { const [current, previous] = useAtomValue(historyAtom) ...}withHistory 创建一个原子,用于追踪指定 targetAtom 的状态历史。最近的 limit 个状态会被保留。
Action Symbols
Section titled “Action Symbols”-
RESET 清除所有历史记录,移除所有先前的状态(包括撤销/重做栈)。
import { RESET } from 'jotai-history'...function Component() {const setHistoryAtom = useSetAtom(historyAtom)...setHistoryAtom(RESET)} -
UNDO 和 REDO 将
targetAtom在历史记录中前移或后移。import { REDO, UNDO } from 'jotai-history'...function Component() {const setHistoryAtom = useSetAtom(historyAtom)...setHistoryAtom(UNDO)setHistoryAtom(REDO)}
-
canUndo 和 canRedo 布尔值,指示当前是否可以执行撤销或重做操作。可用于禁用按钮或条件性地触发操作。
...function Component() {const history = useAtomValue(historyAtom)return (<><button disabled={!history.canUndo}>Undo</button><button disabled={!history.canRedo}>Redo</button></>)}
由于
withHistory维护了一个先前状态的列表,请通过设置合理的limit值来注意内存使用。频繁更新状态的应用可能会导致内存使用量显著增长。