你如何使用 Flux 管理异步 Store 操作? [英] How do you manage asynchronous Store operations with Flux?

查看:37
本文介绍了你如何使用 Flux 管理异步 Store 操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Facebook 关于 Flux 架构的演讲中,Jing 在 12:17 提到

这里的调度程序是强制执行没有级联效果的主要部分;一旦一个动作进入商店,你就不能再放入另一个动作,直到商店完全处理完它.

那么,我的问题是,您如何正确处理可能从存储中启动的长时间运行的异步操作(例如 Ajax 请求,或处理其他一些外部异步 API)——任何阻止完成动作分派(例如,等待使用 Ajax 请求的结果来解决承诺)可能会阻止用户分派 UI 生成的动作.

解决方案

在我看来,依赖 Ajax 等的异步操作不应该阻止将操作分派给所有订阅者.

您将为用户操作设置一个单独的操作,例如 TodoMVC 示例中的 TODO_UPDATE_TEXT 以及在服务器返回时调用的操作,例如 TODO_UPDATE_TEXT_COMPLETED(或也许只是更通用的东西,比如包含最新属性的新副本的 TODO_UPDATE_COMPLETED).

如果您希望进行乐观更新以立即向用户显示其更改的影响,您可以立即更新存储以响应用户操作(然后在服务器返回权威数据时再次更新).如果您想在服务器上等待,您可以让商店只更新自身以响应服务器触发的操作.

In the Facebook talk on the Flux architecture, Jing mentions at 12:17 that the dispatcher enforces that no actions can be dispatched until the current action is fully processed by the stores.

The dispatcher here is the main piece that enforces that there's no cascading effects; once an action goes into the store, you can't put another one in until the stores are completely finished processing it.

My question, then, is how do you properly deal with long-running asynchronous operations that might be kicked off from the store (e.g. an Ajax request, or dealing with some other outside async API)—anything that blocks the completion of the action dispatch (for instance, waiting to resolve a promise with the result of an Ajax request) could block UI-generated actions from the user from being dispatched.

解决方案

In my understanding, asynchronous actions that rely on Ajax, etc. shouldn't block the action from being dispatched to all subscribers.

You'll have a separate action for the user action, like TODO_UPDATE_TEXT in the TodoMVC example and one that gets called when the server returns, something like TODO_UPDATE_TEXT_COMPLETED (or maybe just something more generic like TODO_UPDATE_COMPLETED that contains a new copy of the latest attributes).

In cases where you want to do optimistic updates to show the user the effects of their change immediately, you can update the store in response to the user action immediately (and then once again when the server returns with the authoritative data). If you want to wait on the server, you can have the store only update itself in response to the server-triggered actions.

这篇关于你如何使用 Flux 管理异步 Store 操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆