在 React 中实现 undo/redo 函数

Implementing undo/redo function in react

我正在尝试在我的 React 应用程序中实现简单的 undo/redo 功能。所以我试图维护一个具有旧状态值的数组。但是当我检查旧状态的值时,它全部更新为新状态。

状态:

state = {
        schedule : [],
        loads:[],
        undo:[],
        redo:[]
    };

const redoUndoObj ={
        oldStateSchedule : [...this.state.schedule],
        oldStateLoads : [...this.state.loads]
  }
       
  this.setState({ undo : [ ...this.state.undo , redoUndoObj]});

我希望这能让您对如何解决问题有所了解。我现在只为撤消编写代码,为您指明正确的方向。这个例子是我使用 useState 而不是组件 class.

通过 React 功能组件制作的
    const [schedule, setSchedule] = useState([]);
    const [loads, setLoads] = useState([]);
    const [undo, setUndo] = useState([]);
    const [redo, setRedo] = useState([]);

    const updateData = (newSchedule, newLoads) => {
    setSchedule([...newSchedule]);
    setLoads([...newLoads]);

    const newUndo = {
      schedule: [...newSchedule],
      loads: [...newLoads],
    };

    setUndo([...undo, ...newUndo]);
  }

  const undoChanges = () => {
    const lastElement = undo[undo.length - 1];
    const copyOfUndo = [...undo];
    
    // Update redo to be able to rollback
    setRedo([...undo]);

    // Set the previous values to Schedule and Loads
    schedule([...lastElement.schedule]);
    loads([...lastElement.loads]);

    // Remove the last element from undo
    lastElement.pop();
    undo([...lastElement]);
  }