首页 > 解决方案 > 为什么 Redux-Persist 不持久化存储

问题描述

大家好,我在搞乱反应(准确地说是redux)并遇到了一个问题。当我刷新页面时,redux 商店的一切都恢复到初始值,我用谷歌搜索了这个问题,发现我必须使用redux-persist. 但是即使这样也不起作用,我认为问题在于我如何配置 redux-persist 但我可能是错的。下面的代码是我如何进行 redux-persist 配置的。

// configureStore.js

import { createStore, applyMiddleware } from "redux";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import rootReducer from "../reducers/index";

import { composeWithDevTools } from "redux-devtools-extension";
import thunk from "redux-thunk";

const persistConfig = {
  key: "root",
  storage,
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store = createStore(
  persistedReducer,
  composeWithDevTools(applyMiddleware(thunk))
);

export const persistedStore = persistStore(store);

下面的代码显示了我是如何制作rootReducer.

// index.js
import { combineReducers } from "redux";
import { reducer as formReducer } from "redux-form";

import authReducer from "./auth";
import messageReducer from "./message";
import chatroomReducer from "./chatroom";

import { LOGOUT_SUCCESS } from "../actions/authTypes";

const apiReducer = combineReducers({
  authReducer,
  messageReducer,
  chatroomReducer,
  form: formReducer,
});

const rootReducer = (state, action) => {
  if (action.type === LOGOUT_SUCCESS) {
    state = undefined;
  }
  return apiReducer(state, action);
};

export default rootReducer;

下面的代码是index.js创建 React 应用程序时的代码。

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

import { PersistGate } from "redux-persist/integration/react";
import { Provider } from "react-redux";

import { store, persistedStore } from "./Redux/configureStore";

ReactDOM.render(
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistedStore}>
      <React.StrictMode>
        <App />
      </React.StrictMode>
    </PersistGate>
  </Provider>,
  document.getElementById("root")
);

reportWebVitals();

谁能告诉我我的代码有什么问题?如果您需要更多信息,请告诉我。

标签: reactjsreduxreact-reduxredux-persist

解决方案


尝试配置白名单,您必须在其中指明要存储哪些减速器。请记住在将减速器添加到列表之前导入它们

import navigation from "./reducers/navigation";

// WHITELIST
const persistConfig = {
  key: 'root',
  storage: storage,
  whitelist: ['navigation'] // only navigation will be persisted
};


推荐阅读