我如何在 react.js 中持久化 redux

时间:2021-05-11 11:25:19

标签: reactjs redux redux-persist

我正在做一个项目,我想为我的购物车保留 redux 状态,但似乎遗漏了一些东西。这是我的商店:

import { createStore } from "redux";
import counterReducer from "../store/reducers/reducers";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage"; // defaults to localStorage for web

// const store = createStore(counterReducer);

// export default store;

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

const persistedReducer = persistReducer(persistConfig, counterReducer);

export default () => {
  let store = createStore(persistedReducer);
  let persistor = persistStore(store);
  return { store, persistor };
};

这是我的 index.js:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import "bootstrap/dist/css/bootstrap.min.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import { Provider } from "react-redux";
import store from "./store/";
import persistor from "./store/";
import { PersistGate } from "redux-persist/integration/react";

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

serviceWorker.unregister();

这是我尝试运行我的应用程序时遇到的错误:

TypeError: store.getState is not a function
(anonymous function)
C:/Users/Denoh/wasilisha/Wasilisha_Africa/node_modules/react-redux/es/components/Provider.js:19
  16 |   };
  17 | }, [store]);
  18 | var previousState = useMemo(function () {
> 19 |   return store.getState();
     | ^  20 | }, [store]);
  21 | useEffect(function () {
  22 |   var subscription = contextValue.subscription;
View compiled
mountMemo
C:/Users/Denoh/wasilisha/Wasilisha_Africa/node_modules/react-dom/cjs/react-dom.development.js:15442
  15439 | function mountMemo(nextCreate, deps) {
  15440 |   var hook = mountWorkInProgressHook();
  15441 |   var nextDeps = deps === undefined ? null : deps;
> 15442 |   var nextValue = nextCreate();
  15443 |   hook.memoizedState = [nextValue, nextDeps];
  15444 |   return nextValue;
  15445 | }

请帮我找出我的错误。当我尝试在没有持久库的情况下使用我的 redux 存储时,一切正常。但是坚持下去,我无法追踪我的错误在哪里。

1 个答案:

答案 0 :(得分:1)

您的 store 文件导出 buildStore 函数,而不是 storepersistor

import buildStore from "./store/";
import { PersistGate } from "redux-persist/integration/react";


const {store, persistor} = buildStore()

ReactDOM.render(

始终记住,一个文件只能有一个默认导出,因此如果您将同一文件的默认导入语法用于两个不同的事情,有些事情是可疑的 ;)