waitForSetter

通过传递一个或多个atom或者compute,返回一个新的衍生状态,这个衍生状态可以通过set方法来控制是否更新状态。


function waitForSetter<T extends TMixedRdxValue>(
dependencies: T,
options?: {
// 首次是否更新状态
triggerFirst?: boolean;
// 当重置的时候,是否调用set方法
callSetWhenReset?: boolean;
}
): T extends RdxValue<infer P>
? RdxState<P>
: RdxState<{ [P in keyof T]: UnwrapRdxValue<T[P]> }>;
  • dependencies: 可以是一个 atom 或者是一个 compute,或者是有atom、compute组成的数组或者对象.
  • options
    • triggerFirst 首次是否更新状态
    • callSetWhenReset 当重置的时候是否更新状态

Root

The fallback content to display on prerendering
import React from 'react';
import { atom, useRdxState, RdxContext, useRdxValue, RdxState, waitForSetter, useRdxContext } from '@alife/rdx';
const amountAtom = atom({
id: 'amount',
defaultValue: 1,
});
const unitAtom = atom({
id: 'unit',
defaultValue: 1,
});
export const Root = () => {
return (
<RdxContext>
<View atom={amountAtom} title='数量'/>
<View atom={unitAtom} title='单价' />
<ArrayPreview />
</RdxContext>
);
};
const ArrayPreview = () => {
const [[amount, unit], set] = useRdxState(waitForSetter([amountAtom, unitAtom]));
return (
<div>
<strong>数组形式参数:</strong>
<button onClick={() => {
set()
}}>点我更新状态</button>
{amount * unit}
</div>
);
};
const View = (props: { title: string, atom: RdxState<number> }) => {
const {title, atom}= props
const [state, setState] = useRdxState(atom);
return (
<div style={{ display: 'flex', width: 200 }}>
<strong>title </strong>
{/* 通过传递新的值来更新数据 */}
<button
onClick={() => {
setState(state + 1);
}}
>
+
</button>
<span>{state}</span>
{/* 通过传递updated function 来更新数据 */}
<button
onClick={() => {
setState((state) => {
return state - 1;
});
}}
>
-
</button>
</div>
);
};