我将localStorage用作我的持久redux状态,代码如下所示。
export const loadState = () => {
try {
// localStorage.clear();
const serializedState = localStorage.getItem("state");
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("state", serializedState);
} catch (err) {
// Ignore write errors.
}
};
每次更改逻辑缩减器时,由于要更新localStorage,因此应运行localStorage.clear();
,以便项目可以正确运行。但是,每次都运行清除方法是没有用的,最好是在将项目部署到客户端之后,有一种方法可以控制一次此运行。
答案 0 :(得分:1)
将version
添加到localStorage
并比较何时从化简器初始化状态
在加载状态之前,请保存版本号
// When you update your reducers increase this
// version to 0.2 => 0.3 => 0.4
// this should run before you call loadState
localStorage.setItem('version', '0.3');
export const loadState = () => {
try {
const version = localStorage.getItem('version');
// When you update your reducers change this comparison
// to the version number you set in localStorage
if (version !== '0.1') {
// Let reducers initial the state if the version is not identical
return undefined;
}
const serializedState = localStorage.getItem('state');
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('state', serializedState);
} catch (err) {
// Ignore write errors.
}
};
答案 1 :(得分:0)
您可以使用redux-persist的迁移功能。有关更多详细信息:https://github.com/rt2zz/redux-persist/blob/master/docs/migrations.md