1. 安装 npm i redux-persist
2. 引入
import { persistStore } from 'redux-persist'
import { PersistGate } from 'redux-persist/lib/integration/react'
3.
ReactDOM.render(
<Provider store={store}>
<PersistGate loading={null} persistor={persistStore(store)}>
<Router />
</PersistGate>
</Provider>,
document.getElementById('root')
)
4. store.js 文件
import { persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage'
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2'
// 我要对哪些 reduce 的 state 做数据持久化
const rootPersistConfig = {
key: 'root',
storage,
stateReconciler: autoMergeLevel2,
// 白名单 [reducer 目录内的 reduce 文件名]
whitelist: ['list'],
}
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
// 抽离出一个需要持久化的公共 reduce
const myPersistReducer = persistReducer(
rootPersistConfig,
combineReducers({
lx,
form,
list,
}
))
// createStore(reduce, 中间件)
const store = createStore(
myPersistReducer,
composeEnhancers(applyMiddleware(thunk, promise))
)
export { store }