如何将redux存储到本地存储中

时间:2018-01-13 20:28:36

标签: javascript reactjs redux

无法使用redux-persist将存储持久存储到localstorage。 有错误:

  

商店没有有效的减速机。确保参数传递给   combineReducers是一个值为reducers的对象。

帮助配置商店或有其他方式

import {applyMiddleware, compose, createStore} from "redux";
import thunk from "redux-thunk";
import {createLogger} from "redux-logger";
import rootReducer from "../reducer/index";
import {loadState, saveState} from "../utils";
import { persistStore, persistCombineReducers } from 'redux-persist';
import storage from 'redux-persist/lib/storage';

const config = {
    key: 'root',
    storage,
}

const reducer = persistCombineReducers(config, rootReducer)


function configureStore(initialState) {
    let createStoreWithMiddleware;

const middleware = process.env.__DEV__
    ? applyMiddleware(thunk, createLogger())
    : applyMiddleware(thunk);

createStoreWithMiddleware = compose(
    middleware,
);

const store = createStoreWithMiddleware(createStore)(reducer, initialState);

let persistor = persistStore(store)

if (module.hot) {
    module.hot
        .accept('../reducer', () => {
            const nextRootReducer = require('../reducer/index');
            store.replaceReducer(nextRootReducer);
        });
}


store.subscribe(() => {
    saveState(store.getState().albums)
});

return {store, persistor};

}

export default configureStore

1 个答案:

答案 0 :(得分:0)

由于错误消息已经告知 - 您必须将对象传递给persistCombineReducers方法。

请查看以下example。 (你的一些代码在那里被评论有一个最小的例子。)

所以组合减速器的代码可能是这样的:

const reducer = persistCombineReducers(config, {root: rootReducer});
const store = createStore(reducer, initialState);

如果您只有一台减速机,最好使用:

const reducer = persistReducer(config, rootReducer);