无法存储和从Redux存储中检索状态

时间:2018-08-09 09:35:10

标签: javascript reactjs redux react-redux

import * as actions from '../actions/login.Action';

let initialState = {
    user: {
        loggedIn: false,
        userRole: "",
        userEmail: "",
    }
};

export default function (state = initialState, action) {
    switch (action.type) {
        case actions.LOGIN_SUCCESS:
            return {
                ...state,
                user: {
                    ...state.user,
                    loggedIn: true,
                    userRole: action.userRole,
                }
            };

        case actions.LOGOUT:
            return initialState;

        default:
            return state;
    }
}

这是我在操作登录成功之后触发的减速器,下面是我的商店代码

import { createStore, applyMiddleware, compose } from 'redux';
//import createSagaMiddleware from 'redux-saga';
import { routerMiddleware } from 'react-router-redux';
import thunk from 'redux-thunk';
import createHistory from 'history/createBrowserHistory';
import rootReducer from './reducers';

const enhancers = [];
const middleware = [
    thunk,
    routerMiddleware(history)
];

export const history = createHistory();

const composedEnhancers = compose(
    applyMiddleware(...middleware),
    ...enhancers
);

export const store = createStore(
    rootReducer,
    persistedState,
    composedEnhancers
);


const persistedState = localStorage.getItem('state') ? JSON.parse(localStorage.getItem('state')) : {};


 store.subscribe(() => {
     localStorage.setItem('reduxState', JSON.stringify(store.getState()));
 });

在这种情况下,我能够从reducer中获取值,但问题是状态值在页面上刷新为空刷新此代码中有什么错误,我无法识别出为什么商店不保存状态

1 个答案:

答案 0 :(得分:1)

我认为您先调用persistedState然后定义它,如下所示:

export const store = createStore(
rootReducer,
persistedState,
composedEnhancers
);


const persistedState = localStorage.getItem('state') ? 
JSON.parse(localStorage.getItem('state')) : {};

如何更改persistedState的位置,以使您拥有:

const persistedState = localStorage.getItem('state') ? 
JSON.parse(localStorage.getItem('state')) : {};
export const store = createStore(
  rootReducer,
  persistedState,
  composedEnhancers
 );