useRdxStateLoader(state)
会根据当前参数的 RdxState 来返回 RdxState 的值,状态和设置器,,并且这个 hooks 将会订阅这个 RdxState 的值的变化和值的加载状态。
useRdxStateLoader<GModel>(node: RdxState<GModel>): [LoaderValue<GModel>, TNext<GModel>]
interface LoaderValue<GModel> {
status: Status,
content?: GModel
errorMsg?: string
}
type TNext<GModel> = (value: GModel | ((oldValue: GModel) => GModel)) => void;
enum Status {
Running = 'Running',
Finish = 'Finish',
Waiting = 'Watting',
IDeal = 'IDeal',
Error = 'Error',
}
- state: 可是是一个 atom 或者是一个 compute.
Example#
Root
The fallback content to display on prerendering
import React from 'react';
import {
compute,
RdxContext,
useRdxStateLoader,
atom,
isLoading,
} from '@alife/rdx';
const pause = (t: number) => new Promise((resolve) => setTimeout(resolve, t));
const state = atom({
id: 'atom',
defaultValue: 10,
});
const asyncCompute = compute({
id: 'asyncCompute',
get: async ({ get }) => {
await pause(2000);
return get(state);
},
set: ({ set }, newValue) => {
set(state, newValue);
},
});
export const Root = () => {
return (
<RdxContext>
<Counter />
</RdxContext>
);
};
const Counter = () => {
const [state, setState] = useRdxStateLoader(asyncCompute);
return (
<div style={{}}>
<div>{isLoading(state.status) ? '加载中...' : state.content}</div>
<button
onClick={() => {
setState(state.content + 10);
}}
>
+10
</button>
</div>
);
};