01.状态派生与 Selector

自动生成 Selector

我们建议在使用 store 的属性或动作时使用选择器。你可以像这样访问 store 里的值:

const bears = useBearStore((state) => state.bears);

然而,写这些东西可能很乏味。如果你是这种情况,你可以自动生成你的选择器。

import { StoreApi, UseBoundStore } from "zustand";

type WithSelectors<S> = S extends { getState: () => infer T }
  ? S & { use: { [K in keyof T]: () => T[K] } }
  : never;

const createSelectors = <S extends UseBoundStore<StoreApi<object>>>(
  _store: S
) => {
  let store = _store as WithSelectors<typeof _store>;
  store.use = {};
  for (let k of Object.keys(store.getState())) {
    (store.use as any)[k] = () => store((s) => s[k as keyof typeof s]);
  }

  return store;
};

如果有如下的 Store:

interface BearState {
  bears: number;
  increase: (by: number) => void;
  increment: () => void;
}

const useBearStoreBase = create<BearState>()((set) => ({
  bears: 0,
  increase: (by) => set((state) => ({ bears: state.bears + by })),
  increment: () => set((state) => ({ bears: state.bears + 1 })),
}));

即可生成如下可直接访问的 store:

const useBearStore = createSelectors(useBearStoreBase);

// get the property
const bears = useBearStore.use.bears();

// get the action
const increase = useBearStore.use.increment();
上一页
下一页