Redux 实现撤销、重做

本文介绍了如何在Redux中实现撤销和重做功能。Redux的不可变状态和action机制使其易于实现这一功能。通过使用Redux Undo库,我们可以轻松地添加撤销重做的能力。文章涵盖了安装过程、实现原理以及如何结合undoable()函数与combineReducers来管理状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

实现原理

  1. reducer enhancer(或者 higher order reducer)作为一个函数,接收 reducer 作为参数并返回一个新的 reducer,这个新的 reducer 可以处理新的 action,或者维护更多的 state,亦或者将它无法处理的 action 委托给原始的 reducer 处理。
  2. 使用其中的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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值