redux-persist:如何在浏览器的本地存储上保存状态?

时间:2017-11-06 04:57:44

标签: javascript reactjs react-redux redux-persist

我正在学习redux并且想知道如何在本地保存状态,所以当我在对状态进行一些更改之后刷新它仍然存在。我开始了解redux-persist并看到github doc描述了如何使用它,但对我来说不是很清楚。

这是我的应用程序的index.js代码 -

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';

import App from './components/app';
import reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware()(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <App />
  </Provider>
  , document.querySelector('#container'));

我怎样才能实现它?

2 个答案:

答案 0 :(得分:1)

//In your createStore have this code    
import { applyMiddleware, compose, createStore } from 'redux'
import thunkMiddleware from 'redux-thunk';
import { createLogger } from 'redux-logger';
import rootReducer from '../reducers';
import { persistReducer } from 'redux-persist'
import localForage from 'localforage';
const loggerMiddleware = createLogger();

export default (initialState = {}) => {
  // ======================================================
  // Middleware Configuration
  // ======================================================
  const middleware = [thunkMiddleware, loggerMiddleware]

  // ======================================================
  // Store Enhancers
  // ======================================================



  const enhancers = []
  const __DEV__ = process.env.NODE_ENV !== 'production';
  if (__DEV__) {
    const devToolsExtension = window.devToolsExtension
    if (typeof devToolsExtension === 'function') {
      enhancers.push(devToolsExtension())
    }
  }

  // ======================================================
  // Store Instantiation and HMR Setup
  // ======================================================
  let config = {
    key: 'root',
    storage: localForage,
    whitelist: ['user'],
    debug: __DEV__
  }
  let configureReducer = persistReducer(config, rootReducer)
  const store = createStore(
    configureReducer,
    initialState,
    compose(
      applyMiddleware(...middleware),
      ...enhancers
    ),
  )

  return store
}


// In your App.js or root app, do this in your componentDidMount

persistStore(
      store,
      undefined,
      () => {
        console.log('callback::')
      }
    )

答案 1 :(得分:0)

以下是使用redux-persist中的store.js创建商店应采取的措施:

    import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
    import { persistStore, autoRehydrate } from 'redux-persist';
    import localForage from 'localforage';
    import { routerReducer } from 'react-router-redux';

    import reducers from './container/reducers';
    import middlewares from './middlewares';

    const reducer = combineReducers({
    ...reducers,
    routing: routerReducer,
    });

    export const initStore = (state) => {
    const store = createStore(
        reducer,
        {},
        compose(
        applyMiddleware(...middlewares),
        autoRehydrate(),
        ),
    );

    persistStore(store, {
        storage: localForage,
        whitelist: ['login'],
    });

    return store;
    };

在app.js中,以这种方式创建商店:

import React from 'react';

import { Provider } from 'react-redux';
import { browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';

import createRoutes from './routes'; // Contains the routes
import { initStore, persistReduxStore } from './store';
import { appExample } from './container/reducers';

const store = initStore(appExample);

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { rehydrated: false };
  }

  componentWillMount() {
    persistReduxStore(store)(() => this.setState({ rehydrated: true }));
  }

  render() {
    const history = syncHistoryWithStore(browserHistory, store);
    return (
      <Provider store={store}>
        {createRoutes(history)}
      </Provider>
    );
  }
}