【问题标题】:Persist nested state object using redux-persist使用 redux-persist 持久化嵌套状态对象
【发布时间】:2019-04-14 05:09:34
【问题描述】:

我正在尝试使用redux-persist API 来保持我的状态。我的状态结构如下。

var initState = {
  searchInp: "",
  allProducts: {},
  isProductDtlsLoading: true
};

其中allProducts 是一个嵌套对象数组,每个对象结构如下:

allProducts : {
004: {
   defaultOffer: null
   mrp: 550
   productData: [{…}]
   productName: "Hair Dryer"
   productQty: 0
   sellingPrice: 450
   prodCode: "004"
   }
}

现在,当我尝试持久化数据时,我可以看到应用程序选项卡中的 Chrome 开发人员工具,searchInp 的值保持正常并且不会由于页面刷新而丢失。 allProducts 的值在持久存储中更新得很好,但是当刷新时值会丢失,假设 productQty 默认为 0。 在这种情况下,如何保持嵌套对象属性,如 productQty

index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import rootReducer from "./Store/Reducers/reducer";
import thunk from "redux-thunk";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/es/storage/session";
import { PersistGate } from "redux-persist/lib/integration/react";
import hardSet from "redux-persist/lib/stateReconciler/hardSet";

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

var pReducer = persistReducer(persistConfig, rootReducer);

var store = createStore(pReducer, applyMiddleware(thunk));
var persistor = persistStore(store);

var app = (
  <Provider store={store}>
    <PersistGate persistor={persistor} loading={null}>
      <App />
    </PersistGate>
  </Provider>
);

ReactDOM.render(app, document.getElementById("root"));

【问题讨论】:

    标签: javascript reactjs redux session-storage redux-persist


    【解决方案1】:

    我的应用中有相当复杂的状态,这种方式对我很有效: https://stackoverflow.com/a/37690899/7317796

    【讨论】:

      【解决方案2】:

      很可能你正在改变你的状态而不是用新的替换。 redux-persist 依赖于状态是不可变的这一事实,并且它应该正确地保留更改,除非它们已被变异,请参阅此处https://github.com/rt2zz/redux-persist/issues/623 的一些讨论。因此,请确保您正确更新状态并使用嵌套对象可能会很棘手,这里有一些关于 Cleaner/shorter way to update nested state in Redux?

      的信息

      【讨论】:

        猜你喜欢
        • 2018-08-14
        • 1970-01-01
        • 2022-11-11
        • 1970-01-01
        • 2022-12-31
        • 2017-10-08
        • 1970-01-01
        • 2019-09-20
        • 1970-01-01
        相关资源
        最近更新 更多