我希望将状态树的某些部分持久化到localStorage。在什么地方这样做是合适的?减速剂还是动作剂?
发布于 2016-02-28 04:52:01
Reducer从来都不是一个合适的地方,因为Reducer应该是纯的,没有副作用。
我建议在订阅者中这样做:
store.subscribe(() => {
// persist your state
})
在创建存储之前,请阅读这些持久化部分:
const persistedState = // ...
const store = createStore(reducer, persistedState)
如果您使用combineReducers()
,您会注意到没有接收到状态的reducers将使用其默认的state
参数值正常“启动”。这可能非常方便。
建议您取消订阅,这样就不会太快地写入localStorage,否则会出现性能问题。
最后,您可以创建一个中间件,将其封装为替代方案,但我会从订阅者开始,因为它是一个更简单的解决方案,并且工作做得很好。
发布于 2016-06-08 07:12:13
为了填补丹·阿布拉莫夫答案中的空白,你可以像这样使用store.subscribe()
:
store.subscribe(()=>{
localStorage.setItem('reduxState', JSON.stringify(store.getState()))
})
在创建存储之前,检查localStorage
并解析密钥下的任何JSON,如下所示:
const persistedState = localStorage.getItem('reduxState')
? JSON.parse(localStorage.getItem('reduxState'))
: {}
然后将此persistedState
常量传递给createStore
方法,如下所示:
const store = createStore(
reducer,
persistedState,
/* any middleware... */
)
发布于 2018-02-15 14:04:04
如果任何人对上面的解决方案有任何问题,你可以写你自己的。让我给你看看我做了什么。忽略saga middleware
的事情只关注localStorageMiddleware
和reHydrateStore
方法这两件事。localStorageMiddleware
拉出所有redux state
并将其放入local storage
,rehydrateStore
拉出本地存储中的所有applicationState
并将其放入redux store
import {createStore, applyMiddleware} from 'redux'
import createSagaMiddleware from 'redux-saga';
import decoristReducers from '../reducers/decorist_reducer'
import sagas from '../sagas/sagas';
const sagaMiddleware = createSagaMiddleware();
/**
* Add all the state in local storage
* @param getState
* @returns {function(*): function(*=)}
*/
const localStorageMiddleware = ({getState}) => { // <--- FOCUS HERE
return (next) => (action) => {
const result = next(action);
localStorage.setItem('applicationState', JSON.stringify(
getState()
));
return result;
};
};
const reHydrateStore = () => { // <-- FOCUS HERE
if (localStorage.getItem('applicationState') !== null) {
return JSON.parse(localStorage.getItem('applicationState')) // re-hydrate the store
}
}
const store = createStore(
decoristReducers,
reHydrateStore(),// <-- FOCUS HERE
applyMiddleware(
sagaMiddleware,
localStorageMiddleware,// <-- FOCUS HERE
)
)
sagaMiddleware.run(sagas);
export default store;
https://stackoverflow.com/questions/35305661
复制相似问题