Redux实现撤销、重做

mac2024-06-02  47

Redux 实现撤销重做

因为以下三个原因, Redux 轻而易举地实现撤销重做:

不存在多个模型的问题,你需要关心的只是 state 的子树。

state 是不可变数据,所有修改被描述成独立的 action,而这些 action 与预期的撤销堆栈模型很接近了。

reducer 的签名 (state, action) => state 可以自然地实现 “reducer enhancers” 或者 “higher order reducers”。它们在你为 reducer 添加额外的功能时保持着这个签名。撤销历史就是一个典型的应用场景。

Redux Undo

Redux Undo是一個提供撤销功能的reducer enhancer 库

安装

npm install --save redux-undo

实现原理

reducer enhancer(或者 higher order reducer)作为一个函数,接收 reducer 作为参数并返回一个新的 reducer,这个新的 reducer 可以处理新的 action,或者维护更多的 state,亦或者将它无法处理的 action 委托给原始的 reducer 处理。使用其中的undoable()方法会将state变成这种形式:{ past: [...pastStatesHere...], present: {...currentStateHere...}, future: [...futureStatesHere...] }

undoable()

import undoable from 'redux-undo'; undoable(reducer) undoable(reducer, config)

和combineReducers 配合使用

combineReducers({ counter: undoable(counter) })

undo

import {ActionCreators } from "redux-undo"; store.dispatch(ActionCreators.undo()) // undo the last action 退一步 store.dispatch(ActionCreators.redo()) // redo the last action 进一步 store.dispatch(ActionCreators.jump(-2)) // undo 2 steps store.dispatch(ActionCreators.jump(5)) // redo 5 steps store.dispatch(ActionCreators.jumpToPast(index)) // jump to requested index in the past[] array store.dispatch(ActionCreators.jumpToFuture(index)) // jump to requested index in the future[] array store.dispatch(ActionCreators.clearHistory()) // [beta only] Remove all items from past[] and future[] arrays
最新回复(0)