MobX 操作是否允许显示确认对话框或导航到新屏幕?更一般地说,actions 可以触及 ui 吗?
我正在大型应用程序中重构MobX。由于它很大,所以使代码干净非常重要。
有一个 action
执行以下操作(简化):
@action myAction() {
var data = await api.getSomeDataFromServer();
if (data.warnUser) {
var userAgrees = await showConfirmDialog('Hey, are you really sure?'); // #1
if (!userAgrees) return;
}
someOperations(data);
Navigator.push('/another_page'); // #2
}
我担心 #1
和 #2
是否正常。原因是,恕我直言,mobx 有一个 UI - action - state
三元组(如 mobx 书中的下图所示)。因此,Action
应该修改 State
而不是直接修改 UI
。但在#1
中,Action
直接显示一个对话框——即UI
;在 #2
中,Action
直接导航到另一个页面 - 这也与 UI 相关。
简而言之,MobX 的 action
可以直接“触摸”并操作 ui
吗?
我对此进行了一些搜索,现在很困惑。感谢您的任何建议!
备注:我将其标记为 Flutter 和 JavaScript,因为我确实使用 Flutter,但这个问题也适用于 MobX 的 JS 版本。
备注:以下是mobx书中的图表。
I am refactoring MobX in large-scale applications. Since it is big, making the code clean is very important.
There is an action
that does the following (simplified):
@action myAction() {
var data = await api.getSomeDataFromServer();
if (data.warnUser) {
var userAgrees = await showConfirmDialog('Hey, are you really sure?'); // #1
if (!userAgrees) return;
}
someOperations(data);
Navigator.push('/another_page'); // #2
}
I am worried whether the #1
and #2
are OK or not. The reason is that, IMHO mobx has a UI - action - state
triad (as is seen in the figure below by the mobx book). Thus, Action
s should modify the State
instead of the UI
directly. But in #1
, the Action
directly shows a dialog - which is UI
; in #2
, the Action
directly navigates to another page - which is also UI related.
In short, can MobX's action
s directly "touch" and manipulate the ui
s?
I have made some searches about this and is quite confused now. Thanks for any suggestions!
Remark: I tag it as both Flutter and JavaScript, because indeed I am using Flutter but this question applies to the JS version of MobX as well.
Remark: Following is the diagram from the mobx book.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Mobx 的主要优点之一是使状态和 UI 完全解耦。通过将状态与 UI 解耦,您的测试将更容易编写。您发布的示例很难测试。
我有一些项目,我会编写完整的应用程序业务逻辑,而根本不需要开始处理 UI,然后我只需将状态和状态更改方法挂接到 UI 上。
此外,由于 Mobx 通过将 UI 与状态管理解耦来与 flutter 和 Javascript 配合使用,因此您可以将完整的业务逻辑移植到 Javascript,反之亦然。
总而言之,您的代码可以工作,但它不是 Mobx 方式 :)
例如,您可以 mobx 反应 反应
One of the main advantages of Mobx is making the state and UI completely decoupled. By decoupling the state from the UI, your tests will be far easier to write. The example you posted, would be very hard to test.
I had projects where I would write the complete application business logic without starting to work on the UI at all, then I would just hook the state and state-changing methods to the UI.
Also because Mobx works with flutter and Javascript by decoupling the UI from state management, you could port the complete business logic to Javascript and vice versa.
So to conclude, your code works but it's not the Mobx way :)
For example, you could mobx reaction to react ???? to state changes.
Then somewhere in you UI code
Hope this helps