JotaiJotai

状態
Primitive and flexible state management for React

atomWithDefault

引用: https://github.com/pmndrs/jotai/issues/352

使用

这是一个创建可重置原始原子的函数。 它的默认值可以用读取函数而不是静态初始值来指定。

import { atomWithDefault } from "jotai/utils";
const count1Atom = atom(1);
const count2Atom = atomWithDefault((get) => get(count1Atom) * 2);

Codesandbox

重置默认值

您可以将 atomWithDefault 原子的值重置为其原始默认值。

import { useAtom } from "jotai";
import { atomWithDefault, useResetAtom, RESET } from "jotai/utils";
const count1Atom = atom(1);
const count2Atom = atomWithDefault((get) => get(count1Atom) * 2);
const Counter = () => {
const [count1, setCount1] = useAtom(count1Atom);
const [count2, setCount2] = useAtom(count2Atom);
const resetCount2 = useResetAtom(count2Atom);
return (
<>
<div>
count1: {count1}, count2: {count2}
</div>
<button onClick={() => setCount1((c) => c + 1)}>increment count1</button>
<button onClick={() => setCount2((c) => c + 1)}>increment count2</button>
<button onClick={() => resetCount2()}>Reset with useResetAtom</button>
<button onClick={() => setCount2(RESET)}>Reset with RESET const</button>
</>
);
};

当使用 set 函数覆盖 atomWithDefault 原子值时,这可能很有用,在这种情况下,不再使用提供的 getter 函数,并且依赖原子中的任何更改都不会触发更新。

重置值允许我们恢复其原始默认值,丢弃之前通过 set 函数所做的更改。