React redux-persist through persistent data storage

In React project, we often react-redux redux as well as to store and manage global data. But when the global data storage by redux, there will be such a problem if the user refreshes the page, then we will all be cleared by redux global data storage, such as login information.

This time, we will have a persistent global data storage needs. The first thing we think of is localStorage, localStorage is no time limit for data storage, we can achieve persistent storage of data through it.

However, we have used redux to manage and store global data base, go to read and write data using localStorage, this is not only a huge amount of work, but also prone to error. Then there is no binding redux framework to achieve persistent data storage function of it? Of course, it is the redux-persist. Cached data will redux redux-persist in the store to the browser in localStorage.

Use of redux-persist

1, reducer and action for processing the same, simply modify the generated code store, modified as follows

import {createStore} from 'redux'
import reducers from '../reducers/index'
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, reducers)

const store = createStore(myPersistReducer)

export const persistor = persistStore(store)
export default store

 

2, in index.js, the PersistGate label as a parent tag web content

import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux'
import store from './redux/store/store'
import {persistor} from './redux/store/store'
import {PersistGate} from 'redux-persist/lib/integration/react';

ReactDOM.render(<Provider store={store}>
            <PersistGate loading={null} persistor={persistor}>
                {/*网页内容*/}
            </PersistGate>
        </Provider>, document.getElementById('root'));

 

This completes the simple application implemented by redux-persist React persistent local data storage

3. Finally, we see the debugging browser cache data localStorage

localStorage.png

Found that the data has been stored in localStorage, then refresh the page, the data will not be lost redux

 

Transfer https://segmentfault.com/a/1190000018150177 , author RaoMeng

Guess you like

Origin www.cnblogs.com/GeniusZ/p/12398253.html