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

這是動作登錄成功后觸發的我的減速器,下面是我的商店代碼

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中獲取值,但是問題是狀態值在頁面上變為空刷新此代碼中有什么錯誤我無法確定為什么存儲區不保存狀態

我認為您首先調用了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
 );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM