我在我的代码中添加了 redux-persist
并且它没有保持状态,相反我总是获得初始状态。
这是我的 root-reducer
import { combineReducers } from "redux";
import { persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import userReducer from "./Users/user-reducer";
import cartReducer from "./Cart/cart-reducer";
const persistConfig = {
key: "root",
storage,
whitelist: ["cart"],
};
const rootReducer = combineReducers({
user: userReducer,
cart: cartReducer,
});
export default persistReducer(persistConfig, rootReducer);
这是我的 store.js
文件
import { createStore, applyMiddleware } from "redux";
import logger from "redux-logger";
import rootReducer from "./root-reducer";
import { persistStore } from "redux-persist";
const middlewares = [logger];
export const store = createStore(rootReducer, applyMiddleware(...middlewares));
export const persistor = persistStore(store);
这是我的 index.js
文件
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
import { Provider } from "react-redux";
import { store, persistor } from "./redux/Store";
import { PersistGate } from "redux-persist/integration/react";
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<BrowserRouter>
<PersistGate persistor={persistor}>
<App />
</PersistGate>
</BrowserRouter>
</Provider>
</React.StrictMode>,
document.getElementById("root")
);
每当我使用初始状态刷新页面时,我都会收到 rehydrated: true
,但在触发某些操作后我会收到 rehydrated: false
。
答案 0 :(得分:1)
检查你的reducer.js并确保文件中reducer的底部是
default:
return state;
而不是
default:
return {
...state,
};```