赞
踩
因为刷新会导致数据的丢失,相比于vue直接监听浏览器的刷新,react中可以通过redux-persist持久化数据存储
sudo yarn add redux-persist --save
store/index.js:(里面接入了react-redux调试工具)
- // 引入 creatStore 创建store
- import { createStore } from 'redux'
- import reducer from '../reducer'
- import { composeWithDevTools } from 'redux-devtools-extension'
-
- // 通过redux-persist持久化数据存储
- import { persistStore, persistReducer } from 'redux-persist';
- import storage from 'redux-persist/lib/storage';
- import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';
-
- const persistConfig = {
- key: 'root',
- storage: storage,
- stateReconciler: autoMergeLevel2 // 查看 'Merge Process' 部分的具体情况
- };
-
- const myPersistReducer = persistReducer(persistConfig, reducer)
- const store = createStore(myPersistReducer, composeWithDevTools())
- export const persistor = persistStore(store)
- export default store
index.js:
- import React from 'react';
- import ReactDOM from 'react-dom';
- import Router from './router.js'
- import { Provider } from 'react-redux'
- // 通过redux-persist持久化数据存储
- import store, { persistor } from './redux/store'
- import { PersistGate } from 'redux-persist/lib/integration/react';
- // 通过redux-persist持久化数据存储
- import * as serviceWorker from './serviceWorker';
- ReactDOM.render(
- <Provider store={store}>
- <PersistGate loading={null} persistor={persistor}>
- <Router />
- </PersistGate>
- </Provider>, document.getElementById('root'));
-
- // If you want your app to work offline and load faster, you can change
- // unregister() to register() below. Note this comes with some pitfalls.
- // Learn more about service workers: https://bit.ly/CRA-PWA
- serviceWorker.unregister();
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。