如何确定 LS(脱水)的状态与 combinereducers 形状匹配以应用于预加载状态?
How to figure out that the state from the LS(dehydrated) matches combinereducer's shape to apply in preloadedstate?
在 Redux 工具包中 Preloadedstate(从本地存储脱水)应该是组合减速器的形状如果形状不正确或在连续更新时添加新的减速器,应用程序可能会崩溃,如何比较组合减速器的形状和形状从本地存储中去除状态。
import { combineReducers, configureStore, getDefaultMiddleware } from '@reduxjs/toolkit';
import { useDispatch } from 'react-redux';
import { CONFIG } from '../config/config';
import * as reducers from './models';
const reHydrateStore = () => {
const data = localStorage.getItem(CONFIG.REDUX_APP_STATE);
if (data) {
return JSON.parse(data);
}
return undefined;
};
export const store = configureStore({
reducer: combineReducers({ ...reducers }),
devTools: CONFIG.ENV === 'development' ? true : false,
middleware: getDefaultMiddleware(),
preloadedState: reHydrateStore(), // **** heads down here *** => may crash if store shape not matches combinre reducer's sstate
});
// persisting store
store.subscribe(
lodash.debounce(() => {
localStorage.setItem(CONFIG.REDUX_APP_STATE, JSON.stringify(store.getState()));
}, 1000),
);
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export const useAppDispatch = (): ReturnType<typeof useDispatch> => useDispatch<AppDispatch>();
这并不是 redux-toolkit 特有的。您正在寻找有关 schema version migrations for redux-persist 的文档。
从本质上讲,作为开发人员,您必须跟踪您的状态的哪些版本相互兼容。该版本将与状态一起保存,您可以引入迁移功能从一个版本转到下一个版本。
在 Redux 工具包中 Preloadedstate(从本地存储脱水)应该是组合减速器的形状如果形状不正确或在连续更新时添加新的减速器,应用程序可能会崩溃,如何比较组合减速器的形状和形状从本地存储中去除状态。
import { combineReducers, configureStore, getDefaultMiddleware } from '@reduxjs/toolkit';
import { useDispatch } from 'react-redux';
import { CONFIG } from '../config/config';
import * as reducers from './models';
const reHydrateStore = () => {
const data = localStorage.getItem(CONFIG.REDUX_APP_STATE);
if (data) {
return JSON.parse(data);
}
return undefined;
};
export const store = configureStore({
reducer: combineReducers({ ...reducers }),
devTools: CONFIG.ENV === 'development' ? true : false,
middleware: getDefaultMiddleware(),
preloadedState: reHydrateStore(), // **** heads down here *** => may crash if store shape not matches combinre reducer's sstate
});
// persisting store
store.subscribe(
lodash.debounce(() => {
localStorage.setItem(CONFIG.REDUX_APP_STATE, JSON.stringify(store.getState()));
}, 1000),
);
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export const useAppDispatch = (): ReturnType<typeof useDispatch> => useDispatch<AppDispatch>();
这并不是 redux-toolkit 特有的。您正在寻找有关 schema version migrations for redux-persist 的文档。
从本质上讲,作为开发人员,您必须跟踪您的状态的哪些版本相互兼容。该版本将与状态一起保存,您可以引入迁移功能从一个版本转到下一个版本。