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是實際的項目鍵,而fullKey是從後端暴露的平面鍵的完整鍵。如果同一名稱在多個儲存設置中存在,則getRxStateStorageInfo的結果中也會返回多個項目。
ts
function hasRxReducer(
name: string,
storageOptions: RxStateStorageOptions,
): Promise<boolean>;
function findRxReducerStorages(
name: string,
): Promise<RxStateResolvedStorage[]>;
function getRxReducerStorageInfo(
name: string,
storageOptions?: RxStateStorageOptions,
): Promise<RxStateStorageInfo[]>;