react redux数据持久化

首先安装:npm i  redux-persist -S

安装以后直接进入src/index.js 写入以下代码   直接拿来用

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

import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

import rootReducer from "./reducers"
 
import {persistStore,persistReducer} from "redux-persist"
import {PersistGate} from "redux-persist/es/integration/react"
import storage from 'redux-persist/es/storage'
const config = {
    key:'root',
    storage,
}

function configureStore(){
    let reducer = persistReducer(config,rootReducer);
    let store = createStore(reducer,applyMiddleware(thunk));
    let persistor = persistStore(store)
    
    return {persistor,store}
}

export default class Hello extends Component{
    render(){
        
        const {persistor,store} = configureStore();
        console.log(111)
        return(
            <Provider store={store}>
                <PersistGate persistor={persistor}>
                    <div>
                        <App />
                    </div>
                </PersistGate>
                
            </Provider>
        )
    }
}
 
ReactDOM.render(<Hello />, document.getElementById('root'));

serviceWorker.unregister();

  

posted @ 2020-03-11 14:19  casf  阅读(1252)  评论(0编辑  收藏  举报