按条件更新 atom
之前所讲述的方法创建出来的 atom,其更新都是无条件的,即便是给 atom 更新一个与 atom 当前相同的值,atom 也会执行一次更新,并触发 React 组件的重新渲染。所以创建一个可以根据值是否相等的条件决定更新与否的 atom,对于 React 渲染的性能提升是有一定好处的。
以下是可以接受一个areEqual
比较函数作为参数的 atom 创建函数代码。
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;
});
}
在这个示例中使用了atomWithReducer
这个用来创建 atom 的函数,这个函数可以创建一个使用reducer
函数更新其值的 atom,其函数签名如下。
function atomWithReducer<Value, Action>(
initialValue: Value,
reducer: (value: Value, action?: Action) => Value
): WritableAtom<Value, [Action?], void>;
在上面的示例中使用atomWithReducer
的时候,atom 被赋予的新值实际上是被作为了action
参数传入了reducer
函数中,所以就可以达到按条件更新的目的。