简体   繁体   English

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

[英]Unable to store and retrieve the state from redux store

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;
    }
}

this is my reducer triggered after the action login success and below is my store code 这是动作登录成功后触发的我的减速器,下面是我的商店代码

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()));
 });

in this case I am able to get the value from reducer but the issue is state value gets empty on page refresh whats wrong in this code i'm unable to identify clueless why the store doesn't save the state 在这种情况下,我能够从reducer中获取值,但是问题是状态值在页面上变为空刷新此代码中有什么错误我无法确定为什么存储区不保存状态

I think you first call persistedState then define it Look below : 我认为您首先调用了persistedState然后对其进行了定义,如下所示:

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


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

How about to change the position of persistedState so after that you have : 如何更改persistedState的位置,以便在之后有:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM