首页 > 解决方案 > 自定义 Redux 撤消 reducer 状态变量无法识别

问题描述

为了实现自定义撤消/重做功能,我按照https://redux.js.org/recipes/implementing-undo-history中的说明进行了修改以适应我自己的减速器。现在,当我尝试运行代码时,我得到了过去、现在和未来未定义的错误。该错误不会出现在最初的情况下,而只会出现在ActionTypes.LAYOUT_SET_MOVES,ActionTypes.LAYOUT_UNDO_MOVESActionTypes.LAYOUT_REDO_MOVES情况下。

我已经搜索了代码并将状态变量与其他减速器进行了比较,但没有发现明显的原因。如果您能指出我正确的方向,我将不胜感激。

完整的减速器代码如下。

谢谢。

export const layout_moveData = (state = {
    past: [],
    present: null,
    future: []
}, action) => {

    switch (action.type) {
        case ActionTypes.LAYOUT_DESKS_LOADED:
            return { ...state, present: action.payload, past: [], future: [] };
        case ActionTypes.LAYOUT_RESTORE_ALL:
            return { ...state, present: action.payload, past: [], future: [] };
        case ActionTypes.LAYOUT_SET_MOVES:
            let previousSet = [...past, present];
            return { ...state, past: previousSet, present: action.payload, future: [] };
        case ActionTypes.LAYOUT_UNDO_MOVES:
            if (past.length === 0) return state;
            let previous = past[past.length - 1];
            let newPast = past.slice(0, past.length - 1);
            return { ...state, past: newPast, future: [present, ...future], present: previous };
        case ActionTypes.LAYOUT_REDO_MOVES:
            let next = future[0]
            let newFuture = future.slice(1)
            return { ...state, past: [...past, present], present: next, future: newFuture };
        default:
            return state

    }

标签: reactjsreduxredux-reducers

解决方案


在访问 reducer 中的状态变量时,我需要使用 this.state.past、this.state.present 和 this.state.future,而我在 switch 中返回的值使用简单的过去、现在和未来变量定义新状态.


推荐阅读