使用Redux-Persists,如何将Reducer的初始状态设置为存储在本地存储中的状态?

wyyhbhjk  于 2023-11-19  发布在  其他
关注(0)|答案(2)|浏览(88)

我正在使用Ionic 7,React 18,Redux-Toolkit和Redux-Persists。我想将我的一个状态(cart)持久化到本地存储。我已经设置了我的cartSlice如下

interface CartState {
  [key: string]: OrderItem[];
}

const initialState: CartState = {};

const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    ...
    },

    clearCart: (state) => {
      ...
    },
  },
});

export const {
  addToCart,
  clearCart,
} = cartSlice.actions;

export default cartSlice.reducer;

字符串
并设置我的根持久化还原器如下

const rootPersistConfig = {
  key: 'root',
  storage: storage,
  blacklist: ['auth'],
  stateReconciler: autoMergeLevel2
};

const authPersistConfig = {
  key: 'auth',
  storage: sessionStorage,
}

const rootReducer = combineReducers({
  auth: persistReducer(authPersistConfig, authReducer),
  cart: cartReducer,
})

const persistedReducer = persistReducer(rootPersistConfig, rootReducer);

export default persistedReducer;


我将它加载到我的存储中,如下所示

export const store = configureStore({
  reducer: persistedReducer, // rootReducer,
  devTools: import.meta.env.VITE_NODE_ENV !== "production",
});


我不清楚的是如何将我的初始状态设置为本地存储,假设那里已经有东西了。每次我加载我的应用程序时,我的初始状态都会重置为“{}",这是因为我在切片中设置了它,但我不知道如何告诉我的状态,如果状态已经存在,初始状态可以从本地存储加载。

vdzxcuhz

vdzxcuhz1#

确保您遵循所有设置/配置步骤。

const rootPersistConfig = {
  key: "root",
  storage: storage,
  blacklist: ["auth"],
  stateReconciler: autoMergeLevel2
};

const authPersistConfig = {
  key: "auth",
  storage: sessionStorage
};

const persistedAuthReducer = persistReducer(authPersistConfig, authReducer);

const rootReducer = combineReducers({
  auth: persistedAuthReducer,
  cart: cartReducer
});

const persistedReducer = persistReducer(rootPersistConfig, rootReducer);

const store = configureStore({
  reducer: persistedReducer // rootReducer,
  devTools: import.meta.env.VITE_NODE_ENV !== "production",
});

const persistor = persistStore(store); // <-- persist store

...

<Provider store={store}>
  <PersistGate persistor={persistor}> // <-- persist gate
    ....
  </PersistGate>
</Provider>

字符串
x1c 0d1x的数据

bvhaajcl

bvhaajcl2#

您可以在rootPersistConfig配置对象中使用stateReconciler选项,以确保从本地存储(如果可用)填充cart的初始状态。stateReconciler函数负责将本地存储中的持久化状态与reducer的默认初始状态相结合。
下面是如何使用stateReconciler函数的示例:

const stateReconciler = (storeState, persistedState) => {
  // Check if there's cart data in local storage
  if (persistedState.cart) {
    // Merge the persisted cart data with the default initial state
    return {
      ...storeState,
      cart: persistedState.cart,
    };
  }

  // If no cart data exists in local storage, use the default initial state
  return storeState;
};

字符串
rootPersistConfig配置中还包括以下函数:

const rootPersistConfig = {
  key: 'root',
  storage: storage,
  blacklist: ['auth'],
  stateReconciler: stateReconciler,
};


购物车的初始状态将从本地存储(如果此设置可用)填充,以确保购物车在页面重新加载或应用重新启动之间保持持久性。

相关问题