开发者问题收集

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

2023-11-01
488

我正在使用 Ionic 7、React 18 以及 Redux-Toolkit 和 Redux-Persist。我想将我的一个状态(购物车)持久化到本地存储。我已按如下方式设置了 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;

并按如下方式设置了根持久化 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",
});

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

2个回答

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

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>

Edit with-redux-persist-how-do-i-set-the-initial-state-of-my-reducer-to-be-what-is-s

Drew Reese
2023-11-09

您可以使用 rootPersistConfig 配置对象中的 stateReconciler 选项来确保购物车的初始状态从本地存储(如果可用)填充。 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,
};

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

rain developer
2023-11-08