我正在尝试使用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"));
答案 0 :(得分:0)
我的应用程序状态非常复杂,这种方式对我来说很好: https://stackoverflow.com/a/37690899/7317796
答案 1 :(得分:0)
很可能您是在更改状态,而不是用新状态替换。 redux-persist
依赖于以下事实:状态是不可变的,除非更改已经被更改,否则状态应该正确地保留更改,请参见此处的讨论https://github.com/rt2zz/redux-persist/issues/623。因此,请确保您正确更新状态并使用嵌套对象比较麻烦,这是有关Cleaner/shorter way to update nested state in Redux?