首页 > 解决方案 > 在 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")
    }
}

标签: swiftreduxreswift

解决方案


推荐阅读