swift - 在 ReSwift/Redux 中处理异步请求的好方法是什么
问题描述
为了发出异步请求,在这种情况下使用中间件,它会在固定时间后返回错误。
应用程序状态已正确更新,订阅者视图控制器出现错误。
然而,在下一个实例中,这个订阅者视图控制器出现了,它会在状态中发现错误——这实际上是来自上一个请求的错误,并在请求被触发之前显示错误消息。
如何在 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")
}
}
解决方案
推荐阅读
- android - 使用加速度计了解手机的运动速度并做出反应(Android Studio)
- sql - 使用 uniq ID 对日期范围和岛屿进行分组,而无需按分隔符进行分区
- documentation - 我想做文档查看器
- mysql - 如何根据 R Mysql DB 中的时间戳删除表?
- android - 无法使用 Retrofit 2.6.1 成功发送 POST 请求 - JSON 转换器的问题
- node.js - 如何从谷歌云应用引擎服务获取服务器端网络统计信息(如 Webalizer)
- dataframe - 删除火花数据框中的标点符号
- php - 从数据库中获取数据并通过 phpMailer 发送到邮件
- html - 如何区分 HTML 中相同语言的两个字母?
- javascript - 用 JavaScript 制作日历,我怎样才能使循环在 1 的特定日期开始,而不仅仅是隐藏索引