在最近的一個項目中,要求對 redux 數據作持久化處理,通過研究後成功實現,在此記錄一下過程react
咱們能夠使用 redux-persist
對數據作持久化處理git
npm i --save redux-persist
安裝成功後,咱們須要對 store
代碼進行修改,這是個人 store 生成文件github
import {applyMiddleware, createStore, compose} from 'redux'; import {createLogger} from 'redux-logger'; import thunk from 'redux-thunk'; import reducers from '../reducers'; import {persistStore, persistReducer} from 'redux-persist'; import storage from 'redux-persist/lib/storage' const persistConfig = { key: 'milk', # 對於數據 key 的定義 storage, # 選擇的存儲引擎 } # 對 reducers 的封裝處理 const persistedReducer = persistReducer(persistConfig, reducers) let loggerMiddleware = createLogger(); export default function configureStore() { const enhancers = compose( applyMiddleware(thunk, loggerMiddleware), ); # 處理後的 reducers 須要做爲參數傳遞在 createStore 中 const store = createStore(persistedReducer, enhancers) # 持久化 store let persistor = persistStore(store) return {store, persistor} }
在 react-native 中,存儲引擎默認爲 AsyncStorage
Android是以key=>value的形式存儲在本地sqlite中
iOS 是直接存沙盒文件
sql
其中還有不少能夠配置的地方,你們自行參考官方文檔npm
修改完生成 store 代碼後,在入口文件作一次修改,須要引入 PersistGate
來進行二次的組裝redux
import React, {Component} from 'react'; import {Provider} from 'react-redux'; import HomeContainer from './container/HomeContainer' import configureStore from './redux/store' import {PersistGate} from 'redux-persist/integration/react' # 看這裏 const {store, persistor} = configureStore(); class App extends Component { render() { return ( <Provider store={store}> <PersistGate loading={null} persistor={persistor}> <HomeContainer/> </PersistGate> </Provider> ); } } export default App
簡單配置便可,咱們能夠看一下效果react-native