测试已测试 | ✓ |
语言语言 | SwiftSwift |
许可证 | MIT |
发布最后发布 | 2017 年 4 月 |
SwiftSwift 版本 | 3.0 |
SPM支持 SPM | ✗ |
由 Guillermo Peralta Scura 维护。
Swift 实现的 redux-undo,适用于与 ReSwift 一起使用
进行中
假设您的应用状态如下所示
struct State: StateType, Equatable {
var counter: Int = 0
static func ==(lhr: State, rhr: State) -> Bool {
return lhr.counter == rhr.counter
}
}
注意:确保您的状态符合 Equatable 协议非常重要。
您的 reducer 看起来像这样
func reducer(action: Action, state: State?) -> State {
var state = state ?? initialState()
switch action {
case _ as Increase:
state.counter = state.counter + 1
case _ as Decrease:
state.counter = state.counter - 1
default:
break
}
return state
}
struct AppReducer: Reducer {
func handleAction(action: Action, state: State?) -> State {
return reducer(action, state)
}
}
使用 ReSwiftUndo,您可以触发动作,让您回到先前的状态以及最近的状态。
包裹您的状态为 undoable
让状态看起来像这样
public struct UndoableState<T>: StateType {
public var past: [T]
public var present: T
public var future: [T]
}
现在您可以通过下面的方式获取当前状态: state.present
struct AppReducer: Reducer {
func handleAction(action: Action, state: UndoableState<State>?) -> UndoableState<State> {
return undoable(reducer: reducer)(action, state)
}
}
var store = Store<UndoableState<State>>(reducer: AppReducer(), state: nil)
现在您可以触发 撤销
和 重做
动作,并执行类似以下操作:
print(store.state.present.counter) // 0
store.dispatch(Increase())
print(store.state.present.counter) // 1
print(store.state.past[0].counter) // 0
store.dispatch(Undo())
print(store.state.present.counter) // 0
print(store.state.future[0].counter) // 1
store.dispatch(Redo())
print(store.state.present.counter) // 1