在这种情况下,要使用中间件发出异步请求,它会在固定时间后返回错误。
应用状态已正确更新,订阅者视图控制器显示错误。
但是,在下一个实例中,出现了该订户视图控制器时,它会找到状态中的错误-实际上是前一个请求中的错误,并在触发请求之前显示错误消息。
如何在ReSwift / Redux中处理这种情况?
商店
let store = Store(
reducer: appReducer,
state: AppState(),
middleware: [requestMiddleware]
)
状态
struct AppState: StateType {
var isRequestInProgress = false
var result: Result<Bool, NSError>?
}
动作
struct RequestAction: Action {}
struct ReceiveAction: Action {}
struct ErrorAction: Action {
let error: NSError
}
中间件
let requestMiddleware: Middleware<Any> = { dispatch, getState in
return { next in
return { action in
switch action {
case is RequestAction:
DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
store.dispatch(ErrorAction(error: NSError(domain: "", code: -1, userInfo: nil)))
})
default:
break
}
return next(action)
}
}
}
减速器
func appReducer(action: Action, state: AppState?) -> AppState {
var state = state ?? AppState()
switch action {
case is RequestAction:
state.isRequestInProgress = true
case let action as ErrorAction:
state.isRequestInProgress = false
state.result = .failure(action.error)
default: break
}
return state
}
该应用
class ViewController: UIViewController {
@IBAction func presentControllerB(_ sender: Any) {
guard let viewController = storyboard?.instantiateViewController(withIdentifier: "ViewControllerB") else {
return
}
present(viewController, animated: true)
}
}
class ViewControllerB: UIViewController, StoreSubscriber {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
store.subscribe(self)
}
override func viewWillDisappear(_ animated: Bool) {
store.unsubscribe(self)
super.viewWillDisappear(animated)
}
func newState(state: AppState) {
showActivity(state.isRequestInProgress)
switch state.result {
case .none:
break
case .some(.success(_)):
break
case .some(.failure(let error)):
presentError(error)
dismiss(animated: true)
}
}
@IBAction func request(_ sender: Any) {
store.dispatch(RequestAction())
}
private func showActivity(_ show: Bool) {}
private func presentError(_ error: Error) {
print("Error")
}
}