npm install redux-persist
目录:(分模块)
之前未加入持久化的代码:
import { legacy_createStore as createStore } from 'redux'
import { combineReducers } from "redux";
import countReducer from './modules/countReducer'
const reducer = combineReducers({
countReducer
})
const store = createStore(reducer)
export default store
加入持久化后:
import { legacy_createStore as createStore, combineReducers, applyMiddleware } from 'redux'
import countReducer from './modules/countReducer'
import { persistReducer, persistStore } from 'redux-persist'
import storage from 'redux-persist/lib/storage'
const reducer: any = combineReducers({
countReducer
})
const persist_reducer = persistReducer({ key: 'demo', storage }, reducer)
const store = createStore(persist_reducer)
const persist_store = persistStore(store)
const clear_persist_store = () => {
localStorage.removeItem(`persist:demo`)
}
export {
store,
persist_store,
clear_persist_store
}
index.tsx:
浏览器 localStorage: