如何在页面刷新时保持redux状态

时间:2018-02-15 07:04:44

标签: javascript reactjs redux react-redux local-storage

遵循Dan Abramov方法在localStorage中存储状态我执行页面刷新后无法保留应用程序的现有状态。使用redux dev工具,当我登录时,状态被验证并且用户被存储。刷新页面时,日志会清除并返回“@@ INIT”

我的index.js代码

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import rootReducer from './reducers/rootReducer';
import { loadState, saveState } from './localStorage';
import { BrowserRouter } from 'react-router-dom';
import { composeWithDevTools } from 'redux-devtools-extension';

const middleware = [thunk];
const composeEnhancers = composeWithDevTools({
  thunk
});

const persistedState = loadState();
const store = createStore(
  rootReducer,
  persistedState,
  composeEnhancers(applyMiddleware(...middleware))
);

store.subscribe(() => {
  // saves states to localStorage everytime state changes
  saveState(store.getState());
});

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
);
registerServiceWorker();

localStorage.js的代码

export const loadState = () => {
  try {
    const serializedState = localStorage.getItem('state');
    if (serializedState === null) {
      return undefined;
    }
    return JSON.parse(serializedState);
  } catch (err) {
    return undefined;
  }
};

export const saveState = state => {
  try {
    const serializedState = JSON.stringify(state);
    localStorage.setItem('state', serializedState);
    console.log('this is the state', state);
  } catch (err) {
    // Ignore errors
  }
};

2 个答案:

答案 0 :(得分:1)

//忽略错误

不要忽略错误,至少记录它们以查看是否在localstorage中设置了状态或给出了一些错误。

您也可以确认首先将状态保存在localStorage中吗?

答案 1 :(得分:0)

意识到我错误地使用了redux dev工具。遵循Dan Abramov教程有所帮助,但一个好的建议是记录错误,这是我意识到我正常工作的地方。我的错是我使用的是redux检查器,而不是日志监视器!