Implementing undo / redo in Redux

前端 未结 3 753
孤街浪徒
孤街浪徒 2021-02-01 23:02

Background

For a while now I\'ve been wracking my brain as to how you would implement undo / redo in Redux with server interactions (via ajax).

I\'ve come up w

3条回答
  •  猫巷女王i
    2021-02-01 23:36

    Not sure I understand your use case completely, but in my opinion the best way to go about implementing undo/redo in ReactJS is via an immutable model. Once your model is immutable, you can easily maintain a list of states as they change. Specifically, you need an undo list and a redo list. In your example it would be something like:

    1. Starting counter value = 0 -> [0], []
    2. Add 5 -> [0, 5], []
    3. Add 10 -> [0, 5, 15], []
    4. Undo -> [0, 5], [15]
    5. Redo -> [0, 5, 15], []

    The last value in the first list is the current state (that goes into the component state).

    This is a much simpler approach then Commands, since you don't need to define undo/redo logic separately for every action you want to perform.

    If you need to synchronize state with the server, you can do that too, just send your AJAX requests as part of the undo/redo operation.

    Optimistic updates should also be possible, you can update your state immediately, then send your request and in its error handler, revert to state prior to the change. Something like:

      var newState = ...;
      var previousState = undoList[undoList.length - 1]
      undoList.push(newState);
      post('server.com', buildServerRequestFrom(newState), onSuccess, err => { while(undoList[undoList.length-1] !== previousState) undoList.pop() };
    

    In fact I believe you should be able to achieve all the goals you listed with this approach. If you feel otherwise, could you be more specific about what you need to be able to do?

提交回复
热议问题