为什么 Redux-Persist 不持久化存储

时间:2021-03-27 17:11:32

标签: reactjs redux react-redux redux-persist

大家好,我在处理 react(准确地说是 redux)并遇到了一个问题。当我刷新页面时,redux store 一切都恢复到其初始值,我用谷歌搜索了这个问题,发现我必须使用 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;

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

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();

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

2 个答案:

答案 0 :(得分:0)

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

import navigation from "./reducers/navigation";

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

答案 1 :(得分:0)

首先,您需要从 Async 导入存储

import AsyncStorage from '@react-native-community/async-storage';

像这样使用白名单

const persistConfig = {
   key: 'root',
   storage: AsyncStorage,
    whitelist: [
       'user'
    ],
  };

"user" 是您要存储的特定 root reducer