API参考
global-rx-state导出的主要函数和返回形式。
createRxState
如果参数为一个,则为匿名元组模式;如果传递名称,则为命名对象模式。命名模式支持组件内部调用。
ts
// Anonymous tuple mode: module top-level only
const [setCount, getCount, useCount, countSubject, countReady] =
createRxState(0);
// Named object mode
const { setCount, getCount, useCount, countSubject, countReady } =
createRxState(0, "count", { storage: "auto" });createRxStateTuple
当名称在运行时确定但需要元组返回顺序时使用。存储选项可以与命名键一起使用。
ts
const [setDraft, getDraft, useDraft, draftSubject, draftReady] =
createRxStateTuple(
{ content: "" },
`draft:${tabName}`,
{ storage: "sessionstorage" },
);createRxReducer / createRxReducerTuple
ts
const { dispatchCart, getCart, useCart, cartSubject, cartReady } =
createRxReducer(initialCart, cartReducer, "cart", { storage: "auto" });
const [dispatchFilter, getFilter, useFilter] =
createRxReducerTuple(
initialFilterState,
filterReducer,
`workspace-filter:${workspaceId}`,
);存储值
RxStateStorage 包含持久性后端和兼容别名。sessionstorage 和 sessionStorage 使用浏览器的 sessionStorage。
ts
type RxStateStorage =
| "in-memory"
| "auto"
| "indexeddb"
| "IndexedDB"
| "websql"
| "WebSQL"
| "localstorage"
| "localStorage"
| "sessionstorage"
| "sessionStorage";
type RxStateResolvedStorage =
| "in-memory"
| "indexeddb"
| "websql"
| "localstorage"
| "sessionstorage";
interface RxStateStorageOptions {
storage?: RxStateStorage;
name?: string;
storeName?: string;
keyPrefix?: string;
}自动将按顺序选择可用的 localForage 驱动程序:IndexedDB、WebSQL、localStorage。查询 API 的解析存储将返回实际选择的后端,而不是 auto。
存储工具
Named state和reducer的存储可以通过三种工具进行检查。
ts
function hasRxState(
name: string,
storageOptions: RxStateStorageOptions,
): Promise<boolean>;
function findRxStateStorages(
name: string,
): Promise<RxStateResolvedStorage[]>;
function getRxStateStorageInfo(
name: string,
storageOptions?: RxStateStorageOptions,
): Promise<RxStateStorageInfo[]>;hasRxState检查指定存储设置中是否有值。findRxStateStorages返回已确认值的实际后端,getRxStateStorageInfo始终以数组形式返回确认的存储位置。
ts
interface RxStateStorageInfo {
key: string;
storageKey: string;
fullKey: string;
storage: RxStateResolvedStorage;
name: string;
storeName: string;
keyPrefix: string;
}storageKey是实际的item key,fullKey是可以在后端查看的完整key。如果同名存在于多个存储设置中,getRxStateStorageInfo的结果也会返回多个条目。
ts
function hasRxReducer(
name: string,
storageOptions: RxStateStorageOptions,
): Promise<boolean>;
function findRxReducerStorages(
name: string,
): Promise<RxStateResolvedStorage[]>;
function getRxReducerStorageInfo(
name: string,
storageOptions?: RxStateStorageOptions,
): Promise<RxStateStorageInfo[]>;