创建 Atom
atomWithToggle
atomWithToggle创建一个新的原子,它以一个布尔值作为初始状态,并使用一个 setter 函数来切换它。
这避免了为了更新第一个原子的状态而必须设置另一个原子的方式。
import { WritableAtom, atom } from "jotai";export function atomWithToggle(initialValue?: boolean): WritableAtom<boolean, boolean | undefined> {const anAtom = atom(initialValue, (get, set, nextValue?: boolean) => {const update = nextValue ?? !get(anAtom);set(anAtom, update);});return anAtom as WritableAtom<boolean, boolean | undefined>;}
可以提供可选的初始状态作为第一个参数。
setter 函数可以有一个可选的参数来强制一个特定的状态,比如如果你想从它中创建一个 setActive 函数。
这是它的使用方法。
import { atomWithToggle } from "XXX";// 将有一个初始值设置为 trueconst isActiveAtom = atomWithToggle(true);
在一个组件中:
const Toggle = () => {const [isActive, toggle] = useAtom(isActiveAtom);return (<><button onClick={() => toggle()}>isActive: {isActive ? "yes" : "no"}</button><button onClick={() => toggle(true)}>force true</button><button onClick={() => toggle(false)}>force false</button></>);};
atomWithToggleAndStorage
atomWithToggleAndStorage类似于atomWithToggle,但也可以使用atomWithStorage。
这是来源:
import { WritableAtom, atom } from "jotai";import { atomWithStorage } from "jotai/utils";export function atomWithToggleAndStorage(key: string,initialValue?: boolean,storage?: any): WritableAtom<boolean, boolean | undefined> {const anAtom = atomWithStorage(key, initialValue, storage);const derivedAtom = atom((get) => get(anAtom),(get, set, nextValue?: boolean) => {const update = nextValue ?? !get(anAtom);set(anAtom, update);});return derivedAtom;}
以及它是如何使用的:
import { atomWithToggleAndStorage } from "XXX";// 将初始值设置为 false 并存储在 localStorage 中的键“isActive”下const isActiveAtom = atomWithToggleAndStorage("isActive");
在组件中的用法也与 atomWithToggle 相同。
atomWithCompare
atomWithCompare创建原子,当自定义比较函数areEqual(prev, next)为假时触发更新。
这可以通过忽略对您的应用程序无关紧要的状态更改来帮助您避免不需要的 re-render。
注意:Jotai 在内部使用 Object.is 来比较发生变化时的值。 如果 areEqual(a, b) 返回 false,但 Object.is(a, b) 返回 true,则 Jotai 不会触发更新。
import { atomWithReducer } from "jotai/utils";export function atomWithCompare<Value>(initialValue: Value,areEqual: (prev: Value, next: Value) => boolean) {return atomWithReducer(initialValue, (prev: Value, next: Value) => {if (areEqual(prev, next)) {return prev;}return next;});}
以下是您如何使用它来创建一个忽略浅相等更新的原子:
import { atomWithCompare } from "XXX";import { shallowEquals } from "YYY";import { CSSProperties } from "react";const styleAtom = atomWithCompare<CSSProperties>({ backgroundColor: "blue" },shallowEquals);
在一个组件中:
const StylePreview = () => {const [styles, setStyles] = useAtom(styleAtom);return (<div><div styles={styles}>Style preview</div>{/* 单击此按钮两次只会触发一次渲染 */}<button onClick={() => setStyles({ ...styles, backgroundColor: "red" })}>Set background to red</button>{/* 单击此按钮两次只会触发一次渲染 */}<button onClick={() => setStyles({ ...styles, fontSize: 32 })}>Enlarge font</button></div>);};
atomWithRefresh
atomWithRefresh通过使用更新函数创建一个可以强制刷新的派生原子。