当前位置:   article > 正文

通过redux-persist持久化数据存储_persistreducer

persistreducer

因为刷新会导致数据的丢失,相比于vue直接监听浏览器的刷新,react中可以通过redux-persist持久化数据存储

sudo yarn add redux-persist --save

store/index.js:(里面接入了react-redux调试工具)

  1. // 引入 creatStore 创建store
  2. import { createStore } from 'redux'
  3. import reducer from '../reducer'
  4. import { composeWithDevTools } from 'redux-devtools-extension'
  5. // 通过redux-persist持久化数据存储
  6. import { persistStore, persistReducer } from 'redux-persist';
  7. import storage from 'redux-persist/lib/storage';
  8. import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';
  9. const persistConfig = {
  10. key: 'root',
  11. storage: storage,
  12. stateReconciler: autoMergeLevel2 // 查看 'Merge Process' 部分的具体情况
  13. };
  14. const myPersistReducer = persistReducer(persistConfig, reducer)
  15. const store = createStore(myPersistReducer, composeWithDevTools())
  16. export const persistor = persistStore(store)
  17. export default store

index.js:

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import Router from './router.js'
  4. import { Provider } from 'react-redux'
  5. // 通过redux-persist持久化数据存储
  6. import store, { persistor } from './redux/store'
  7. import { PersistGate } from 'redux-persist/lib/integration/react';
  8. // 通过redux-persist持久化数据存储
  9. import * as serviceWorker from './serviceWorker';
  10. ReactDOM.render(
  11. <Provider store={store}>
  12. <PersistGate loading={null} persistor={persistor}>
  13. <Router />
  14. </PersistGate>
  15. </Provider>, document.getElementById('root'));
  16. // If you want your app to work offline and load faster, you can change
  17. // unregister() to register() below. Note this comes with some pitfalls.
  18. // Learn more about service workers: https://bit.ly/CRA-PWA
  19. serviceWorker.unregister();

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/510721
推荐阅读
相关标签
  

闽ICP备14008679号