【问题标题】:How do i do redux persist in react.js我如何在 react.js 中坚持 redux
【发布时间】:2021-05-11 11:25:19
【问题描述】:

我正在做一个项目,我想为我的购物车保留 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 商店时,一切正常。但随着坚持,我无法追踪我的错误在哪里。

【问题讨论】:

    标签: reactjs redux redux-persist


    【解决方案1】:

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

    import buildStore from "./store/";
    import { PersistGate } from "redux-persist/integration/react";
    
    
    const {store, persistor} = buildStore()
    
    ReactDOM.render(
    

    永远记住,一个文件只能有一个默认导出,所以如果你对同一个文件使用默认的导入语法来处理两个不同的事情,有些事情是可疑的;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-09
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多