[英]When using ReSwift with substates, how can I avoid receiving unwanted substate updates, when another substate is updated?
When using ReSwift with substates, how can i avoid receiving unwanted substate update ( SubstateA ), when updating a another substate (SubstateB)当使用ReSwift与子状态,如何避免接收到不想要子状态更新(SubstateA),更新另一个子状态(SubstateB)时
I though that was the whole point haven substates...我虽然这是重点避风港子状态...
State.swift状态.swift
struct MainState: StateType {
var subStateA: SubstateA?
var subStateB: SubstateB?
}
struct SubstateA: StateType {
let value: String
}
struct SubstateB: StateType {
let value: String
}
Store.swift商店.swift
let mainStore = ReSwift.Store<MainState>(reducer: { action, state -> MainState in
var newState = state ?? MainState()
switch action {
case let anAction as UpdateSubstateA:
newState.subStateA = newState.subStateA ?? SubstateA(value: anAction.value)
case let anAction as UpdateSubstateB:
newState.subStateB = newState.subStateB ?? SubstateB(value: anAction.value)
default:
break
}
return newState
}, state: nil)
Actions.swift Actions.swift
struct UpdateSubstateA: Action {
let value:String
}
struct UpdateSubstateB: Action {
let value:String
}
ViewController.swift视图控制器.swift
class ViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
mainStore.subscribe(self) { $0.select { state in (state.subStateB ) } }
mainStore.dispatch(UpdateSubstateA(value: "a"))
mainStore.dispatch(UpdateSubstateB(value: "b"))
}
}
extension ViewController: StoreSubscriber {
func newState(state: SubstateB?) {
print("SubstateB updated")
}
typealias StoreSubscriberStateType = SubstateB?
}
Although I dispatched a single update action for SubstateB I also receive newState events when SubstateA is updated虽然我为 SubstateB 调度了一个更新操作,但当 SubstateA 更新时,我也会收到 newState 事件
Console安慰
SubstateB updated
SubstateB updated
SubstateB updated
Question is old, but maybe an answer will be useful for somebody.问题很老,但也许答案对某人有用。
The subscription could be:订阅可以是:
mainStore.subscribe(self) { $0.select { $0.subStateB }.skipRepeats(==) }
SubstateB should conform to the Equatable protocol: SubstateB 应该符合 Equatable 协议:
extension SubstateB: Equatable {
static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.value == rhs.value
}
}
Console:安慰:
SubstateB updated - nil (initial value)
SubstateB updated - value: "b"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.