部署客户端后如何更新持久性Redux状态?

时间:2018-10-26 02:49:21

标签: javascript reactjs 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,因此应运行localStorage.clear();,以便项目可以正确运行。但是,每次都运行清除方法是没有用的,最好是在将项目部署到客户端之后,有一种方法可以控制一次此运行。

2 个答案:

答案 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