一、数据持久化:一般是指页面刷新后,数据仍然能够保持原来的状态。
一般在前端当中,数据持久化,可以通过将数据存储到localstorage或Cookie中存起来,用到的时
候直接从本地存储中获取数据。而redux-persist是把redux中的数据在localstorage中存起来,起到
持久化的效果。
二、使用:
安装:npm i redux-persist --save
在store.js中使用
//引入createStore,专门用于创建redux中最为核心的store对象
import { createStore } from 'redux'
import {persistStore, persistReducer} from 'redux-persist'
import storage from 'redux-persist/lib/storage'
//引入汇总之后的reducer
import reducers from './reducers'
import loading from '../redux/reducers/loading'
//在localStorge中生成key为root的值
const persistConfig = {
key: 'root',
storage,
blacklist:['loading'] //设置某个reducer数据不持久化,
//注意单词的拼写!我就因为写错单词,找了半天,55555~
}
const myPersistReducer = persistReducer(persistConfig, reducers)
const store = createStore(myPersistReducer)
const persistor = persistStore(store)
export {
store,
persistor
}
在主入口文件,index.js中
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { HashRouter } from 'react-router-dom'
import { store,persistor} from './redux/store'
import { Provider } from 'react-redux';
import './App.css';
import './utils/request'
import {PersistGate} from 'redux-persist/integration/react'
ReactDOM.render(
/* 此处需要用Provider包裹App,目的是让App所有的后代容器组件都能接收到store */
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<HashRouter>
<App />
</HashRouter>
</PersistGate>
</Provider>,
document.getElementById('root')
);
注意项目中store的引入方式为import {store} from'xxx'
三、最终效果