reset redux enhancer,不改变状态的形状

时间:2017-12-19 18:39:22

标签: reactjs redux react-redux

我创建了以下redux增强器,它允许我随时拍摄状态和回滚的快照:

export const resetable = (reducer: Function) => {
  const initialState = { current: reducer(undefined, {}), previous: undefined };

  return (state = initialState, action: Action) => {
    switch (action.type) {
      case ActionTypes.SaveSnapShot:
        return { ...state, previous: state.current };
      case ActionTypes.Rollback:
        return { ...state, current: state.previous, previous: undefined };
      case ActionTypes.Commit:
        return { ...state, previous: undefined };
      default:
        return {
          ...state,
          current: reducer(state.current, action)
        };
    }
  };
};

它的用法是这样的:

export default function createReducer() {
  return combineReducers({
    key: resetable(reducer),
  });
}

问题是它改变了传入的reducer状态的形状。

例如,如果我有这样的状态:

{
  contact: {
    firstName: 'Bob',
    lastName: 'Conman'
  }
}

然后它会向州添加currentprevious个键。

所以状态变为:

{
  contact: {
    current: {
      firstName: 'Bob',
      lastName: 'Conman'
    },
    previous: undefined
  }
}

是否有提供类似功能而不改变状态的形状并添加新密钥?

0 个答案:

没有答案