gpt4 book ai didi

javascript - 无法从 redux 存储中存储和检索状态

转载 作者:行者123 更新时间:2023-12-03 01:21:02 25 4
gpt4 key购买 nike

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

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

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

关于javascript - 无法从 redux 存储中存储和检索状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51763566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com