我有一个Redux Reducer,每次用户选择新选项时,它都需要存储以前选择的选项。
- 用户选择A(返回空数组(
- 用户选择B(返回A(
- 用户选择C(返回B(
- 用户选择D(返回C(
。
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;
}}
当选择发生变化时,将上一个值存储在不同的状态属性中:
case updateSelection:
return {
...state,
previous: state.current,
current: action.payload
}
然后您可以选择以前的值。
与其将状态设为单个对象,不如将其设为两个对象,一个存储上一个值,另一个存储当前值。
逻辑如下:
initialState = { previous: {}, current: {}}
Case updateSelection:
return {
...state,
previous: state.current,
current: action.payload
}
然后,您可以在代码中检查state.previous。