Zustand 持久中间件用初始状态覆盖持久存储

问题描述 投票:0回答:1

我 100% 确定这是我造成的问题,但不知道如何解决。 我有一个带有我想要保留的用户设置的商店(我使用 MMKV 作为商店)。在应用程序上,我将设置设置为 TRUE,并且可以看到我的 MMKV 商店正在获取更新,但是当我关闭并打开或刷新应用程序时,据我所知,我的商店正在使用初始设置进行设置我在 zustand 状态下设置的值。

我通过删除初始状态来测试这一点,这会产生以下结果:

{
  "version": 1
}

然后在应用程序上设置我的设置,这会产生以下结果:

{
    "state": {
      "notifications": {
        "bookings": false,
        "messages": false
      }
    },
    "version": 1
}

但是当我重新加载应用程序时,它会恢复到第一个结果,这就是为什么我认为它正在从初始状态设置商店。

有人能发现这里有问题吗?

const initialState = {
  settings: {
    notifications: {
      bookings: false,
      messages: false,
    },
  },
};

const zustandStorage: StateStorage = {
  setItem: (name, value) => {
    return storage.set(name, value);
  },
  getItem: (name) => {
    let value = storage.getString(name);
    return value ?? null;
  },
  removeItem: (name) => {
    return storage.delete(name);
  },
};

const storage = zustandSorage.getItem('user_settings');

export const createSettingsSlice: StateCreator<
  Settings,
  [],
  [['zustand/persist', unknown]]
> = persist(
  (set, get) => ({
    ...initialState,
    setInitialState: () => {
      checkNotifications()
        .then(async ({ status }) => {
          if (status === 'granted') {
              set(
                produce((state) => {
                  (state.settings.notifications.bookings =
                    storage?.state.notifications.bookings),
                    (state.settings.notifications.messages =
                      storage?.state.notifications.messages);
                })
              );
            }
          } else {
            set(
              produce((state) => {
                (state.settings.notifications.bookings = false),
                  (state.settings.notifications.messages = false);
              })
            );
          }
        });
    },
    setNotification: (value: 'MESSAGES' | 'BOOKINGS') => {
      set(
              produce((state) => {
                (state.settings.notifications.bookings =
                  value === 'BOOKINGS'
                    ? !state.settings.notifications.bookings
                    : state.settings.notifications.bookings),
                  (state.settings.notifications.messages =
                    value === 'MESSAGES'
                      ? !state.settings.notifications.messages
                      : state.settings.notifications.messages);
              })
            );
    },
    resetNotification: () => {
      set(() => initialState);
    },
  }),
  {
    name: 'user_settings',
    storage: createJSONStorage(() => zustandStorage),
    partialize: (state) => state.settings,
    version: 1
  }
);
react-native persist zustand
1个回答
0
投票

您的存储不应该是

const storage = zustandSorage.getItem('user_settings');
。应该是
const storage = new MMKV();

来自 zustand 文档:https://github.com/mrousavy/react-native-mmkv/blob/master/docs/WRAPPER_ZUSTAND_PERSIST_MIDDLEWARE.md

© www.soinside.com 2019 - 2024. All rights reserved.