【问题标题】:Where to put persistedState in Create-Store for saving redux store into localStorage在 Create-Store 中将persistedState 放在哪里以将 redux 存储保存到 localStorage
【发布时间】:2020-01-07 13:37:00
【问题描述】:

我正在尝试使用浏览器 LocalStorage 保存我的 Redux-Store。但我不确定在哪里插入我的persistedState。这是我的代码。

import rootReducer from './Reducers';
import initialState from './Reducers/initialState';

import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const saveToLocalStorage = (state) => {
    try {
        const serializedState = JSON.stringify(state);
        localStorage.setItem('state', serializedState);
    } catch (error) {
        console.log(error);
    }
};
const loadFromLocalStorage = (state) => {
    try {
        const serializedState = localStorage.getItem('state');
        if (serializedState == null) return undefined;
        return JSON.parse(serializedState);
    } catch (error) {
        return undefined;
    }
};
const persistedState = loadFromLocalStorage();
// I inserted my persistedState in createStore but I am getting an error ==> {Expected to be function}
const store = createStore(rootReducer, initialState, persistedState,  composeEnhancers(applyMiddleware(thunk)));


store.subscribe(() => saveToLocalStorage(store.getState()));

export default store;

【问题讨论】:

    标签: reactjs redux redux-thunk


    【解决方案1】:

    这取决于您何时需要该状态,但我想您希望在 init 上加载它,因此将其合并到您的初始状态是有意义的:

    const persistedState = loadFromLocalStorage();
    const store = createStore(rootReducer, {
      ...initialState,
      ...persistedState
    }, composeEnhancers(applyMiddleware(thunk)));
    
    

    【讨论】:

    • 我想将我的ReduxState 加载到LocalStorage,所以当页面刷新时我不会丢失用户信息。谢谢@clarity
    猜你喜欢
    • 1970-01-01
    • 2021-09-27
    • 2020-09-08
    • 2012-01-27
    • 1970-01-01
    • 2011-10-28
    • 2014-10-18
    • 1970-01-01
    相关资源
    最近更新 更多