zustand typescript 持久化如何输入 store

use*_*366 16 typescript reactjs react-state

我有一家简单的商店

interface CartState {
  cart: { [id: string]: CartDto };
  addItem: ({ id, image, name, price }: Omit<CartDto, "quantity">) => void;
  removeItem: (id: string) => void;
  reset: () => void;
}
export const useCart = create<CartState>((set, get) => ({
  cart: {},
  addItem: ({ id, image, name, price }) => {
    set(() => {
      const cart = get().cart;
      if (!cart[id]) {
        cart[id] = {
          id,
          image,
          name,
          price,
          quantity: 0
        };
      }

      cart[id].quantity += 1;

      return { cart };
    });
  },
  removeItem: (id) => {
    set(() => {
      const cart = get().cart;

      if (!cart[id]) {
        return { cart };
      }

      const newQuantity = cart[id].quantity - 1;
      if (newQuantity <= 0) {
        delete cart[id];
      } else {
        cart[id].quantity = newQuantity;
      }

      return { cart };
    });
  },
  reset: () => {
    set(() => {
      return { cart: {} };
    });
  }
}));
Run Code Online (Sandbox Code Playgroud)

而且效果很好。问题是当我尝试添加持久性时

export const useCart = create<CartState>(
  persist(
    (set, get) => ({
      cart: {},
      addItem: ({ id, image, name, price }) => {
        set(() => {
          const cart = get().cart;
          if (!cart[id]) {
            cart[id] = {
              id,
              image,
              name,
              price,
              quantity: 0
            };
          }

          cart[id].quantity += 1;

          return { cart };
        });
      },
      removeItem: (id) => {
        set(() => {
          const cart = get().cart;

          if (!cart[id]) {
            return { cart };
          }

          const newQuantity = cart[id].quantity - 1;
          if (newQuantity <= 0) {
            delete cart[id];
          } else {
            cart[id].quantity = newQuantity;
          }

          return { cart };
        });
      },
      reset: () => {
        set(() => {
          return { cart: {} };
        });
      }
    }),
    {
      name: "cart",
      getStorage: () => localStorage
    }
  )
);
Run Code Online (Sandbox Code Playgroud)

我有这个错误:

类型参数 '(set: SetState, get: GetState, api: StoreApiWithPersist<{ car​​t: {}; addItem: ({ id, image, name, Price }: Omit<CartDto, "quantity">) => void; removeItem : (id: string) => void; 重置: () => void; }>) => { ...; }' 不可分配给类型为“StoreApi | }”的参数 StateCreator<CartState、SetState、GetState、StoreApi>'。
类型 '(set: SetState, get: GetState, api: StoreApiWithPersist<{ car​​t: {}; addItem: ({ id, image, name, Price }: Omit<CartDto, "quantity">) => void; removeItem: ( id: string) => void; 重置: () => void; }>) => { ...; }' 不可分配给类型“StateCreator<CartState, SetState, GetState, StoreApi>”。

我尝试过

export const useCart = create<StoreApiWithPersist<CartState>>
Run Code Online (Sandbox Code Playgroud)

没有运气。

请问什么是正确的方法?

Phi*_*Jay 41

将 zustand 与 TypeScript 一起使用时,您应该使用文档第一段中所述的柯里版本。create<T>(...)

更换

  export const useCart = create<CartState>( 
Run Code Online (Sandbox Code Playgroud)

经过

  export const useCart = create<CartState>()( 
Run Code Online (Sandbox Code Playgroud)

应该可以解决问题。


Avv*_*eyz 8

编辑:PhilJay 的答案是最好的答案。尽管这个答案被标记为最佳答案,但它已经过时了。

我遇到过同样的问题。我所做的是:

import create, { GetState, SetState } from 'zustand';
import { devtools, persist, StoreApiWithPersist } from 'zustand/middleware';

const useAssetStore = create<AssetStoreType, SetState<AssetStoreType>, GetState<AssetStoreType>, StoreApiWithPersist<AssetStoreType>>(
persist(
    devtools((set) => ({
        logo: '',
    })),
    { name: 'assetStore', version: 1, getStorage: () => localStorage }
));
Run Code Online (Sandbox Code Playgroud)

因此,在您的情况下,您需要明确添加:

create<CartState, SetState<CartState>, GetState<CartState>, StoreApiWithPersist<CartState>>
Run Code Online (Sandbox Code Playgroud)