reactjs 在React应用中使用Zustand的持久化中间件和StateCreator的TypeScript错误

x6yk4ghg  于 2023-08-04  发布在  React
关注(0)|答案(1)|浏览(229)

我正在尝试使用Zustand的持久化中间件来存储和检索React应用程序中的状态。然而,我遇到了一个TypeScript错误,我正在努力解决。错误消息如下:

Argument of type 'StateCreator<ForestStore, [], [["zustand/persist", ForestStore]]>' is not assignable to parameter of type 'StateCreator<ForestStore, [], []>'.
Type 'StateCreator<ForestStore, [], [["zustand/persist", ForestStore]]>' is not assignable to type '{ $$storeMutators?: [] | undefined; }'.
Types of property '$$storeMutators' are incompatible.
Type '[["zustand/persist", ForestStore]] | undefined' is not assignable to type '[] | undefined'.
Type '[["zustand/persist", ForestStore]]' is not assignable to type '[]'.
Source has 1 element(s) but target allows only 0.ts(2345)

字符串
下面是我的代码:

import {create} from 'zustand';
import { persist, createJSONStorage} from 'zustand/middleware';

export type Forest = "poetry" | "prose" | "script";
export interface ForestStore {
  forest: Forest;
  setForest: (forest: Forest) => void;
}

const forestPersist = persist<ForestStore>(
    (set) => ({
        forest: "poetry",
        setForest: (newForest) => set(() => ({forest: newForest})),
    }),
    {
        name: "forest-storage",
        storage: createJSONStorage(() => sessionStorage),
    }
);


export const useForestStore = create<ForestStore>(forestPersist);


我真的不知道如何解决它的代码工作的预期,但类型是混乱的。
先谢谢你了

o2gm4chl

o2gm4chl1#

这样写

import { create, StateCreator } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";

export type Forest = "poetry" | "prose" | "script";
export interface ForestStore {
  forest: Forest;
  setForest: (forest: Forest) => void;
}

const forestSlice: StateCreator<ForestStore, [["zustand/persist", unknown]]> = (
  set
) => ({
  forest: "poetry",
  setForest: (newForest) => set(() => ({ forest: newForest })),
});

export const useForestStore = create<ForestStore>()(
  persist(forestSlice, {
    name: "forest-storage",
    storage: createJSONStorage(() => sessionStorage),
  })
);

字符串
如果你有更多的中间件,比如devtoolsimmersubscribeWithSelector,你可以看看我的视频,这个视频中的代码是经过测试的:
https://youtu.be/kTwx9NhMlzs

相关问题