部署客户端后如何更新持久 redux 状态一次?



我使用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.clear();,以更新 localStorage,以便项目可以正常运行。但是每次都运行 clear 方法没有用,最好在将项目部署到客户端后有一种方法来控制一次此运行。

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.
}
};

您可以使用 redux-persist 的迁移功能。 有关更多详细信息:https://github.com/rt2zz/redux-persist/blob/master/docs/migrations.md

最新更新