我有一个使用 Redux 的应用程序。Is 存储全局状态,如下所示:
创建商店:
import {createStore, applyMiddleware} from 'redux';
import rootReducer from '../reducers';
import thunk from 'redux-thunk';
const configureStore = initialState => {
return createStore(
rootReducer,
initialState,
applyMiddleware(thunk)
);
};
export default configureStore;
处理本地存储
const storageName = 'xxxState';
export const loadState = () => {
try {
const serializedState = localStorage.getItem(storageName);
if (serializedState === null) {
return undefined;
}
return JSON.parse(serializedState);
} catch(err) {
return undefined;
}
};
export const saveState = state => {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem(storageName, serializedState);
} catch(err) {
throw err;
}
};
Finaly 启动应用会话:
import React from 'react';
import ReactDOM from 'react-dom';
import Start from './start';
import { Provider } from 'react-redux';
import configureStore from './store/configureStore';
import { loadState, saveState } from './store/localStorage';
import throttle from 'lodash/throttle';
const persistedState = loadState();
const store = configureStore(persistedState);
store.subscribe(throttle(() => {
saveState(store.getState());
}, 1000));
ReactDOM.render(
<Provider store={store}>
<Start />
</Provider>,
document.getElementById('root'));
它完美地工作。所以我的问题是:有没有可能对新的 React Context API 做同样的事情?
使用新的上下文我很舒服,我只想了解商店、本地存储、订阅。因此,即使用户离开应用程序,状态也会保持不变。