【问题标题】:How persist redux store to localstorage如何将 redux store 持久化到 localstorage
【发布时间】:2018-06-22 23:08:20
【问题描述】:

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

Store 没有有效的 reducer。确保参数传递给 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

【问题讨论】:

  • 欢迎来到 Stack Overflow。我不确定你的问题是什么 - 这是你的代码吗?到目前为止,您尝试了哪些方法?
  • 欢迎来到 SO。请完成游览,您将了解How to create a Minimal, Complete, and Verifiable example 并相应地修改问题以最小化工作示例。如果不发布您的代码,您可能会删除您的问题。使用您声明的跟踪和错误代码......人们更愿意帮助您,以便双方都可以学习。问题移至编辑。审核完毕。尽情享受吧 ;-)
  • 正如 Mikkel 所说,它不清楚你的问题。

标签: javascript reactjs redux


【解决方案1】:

正如错误消息已经说明的那样 - 您必须将一个对象传递给 persistCombineReducers 方法。

请查看以下example。 (您的一些代码在那里被注释为一个最小的例子。)

所以你的组合reducer的代码可能是这样的:

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

如果您只有一个减速器,最好使用:

const reducer = persistReducer(config, rootReducer);

【讨论】:

    猜你喜欢
    • 2019-05-12
    • 2021-09-27
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 2021-10-01
    相关资源
    最近更新 更多