Redux reducer return 之前的动态状态

Redux reducer return previous state dynamically

我有一个 Redux Reducer,每次用户选择新选项时都需要存储之前选择的选项。

.

export default function reducer(state = [], action) {
  switch (action.type) {
    case previousSelectionAction.PREVIOUS_SELECTION: {

      // Need to return the previous selection
      // Have tried:
      //  return [...state] and other variations with action.payload and dropping item in array
      // but this just returns the same state, does not update each tie a user selects a new option

    }
default:
  return state;

} }

当select离子改变时,以不同的状态属性存储先前的值:

case updateSelection:
  return {
    ...state,
    previous: state.current,
    current: action.payload
  }

然后您可以 select 之前的值。

与其让你的状态成为一个单一的对象,它可以是 2 个对象,一个存储先前的值,一个存储当前的值。

逻辑将类似于以下内容:

initialState = { previous: {}, current: {}}

Case updateSelection: 
      return {
        ...state, 
        previous: state.current, 
        current: action.payload
      }

然后,您可以在代码中检查 state.previous。