javascript - React-Redux跨模块通信

标签 javascript reactjs model-view-controller redux

在 React Redux 中设置跨模块通信的正确方法是什么?

假设有一个用例,在某些操作中,我需要对多个模块进行更新。这个代码应该放在哪里?

示例 1:模块 A 控制 View A 的操作和 View B 的模块 B 的操作。单击模块 B 中的链接时,我需要向模块 A 和模块 B 分派(dispatch)一些操作。

或者,如果有一个用例,我需要从模块 A 或模块 B 分派(dispatch)一个操作,但模块 A 和模块 B 中都需要执行一些操作。

我应该如何设计我的应用程序,以便它能够正确、干净地处理它? (我在我的应用程序中使用 Ducks 代码排列模式,其中模块由操作 + reducer + 操作创建器组成)

最佳答案

这就是我在概念上不喜欢“鸭子”模式的原因之一。引用我的帖子The Tao of Redux, Part 2 - Practice and Philosophy :

To me, there are a couple conceptual downsides to the "ducks" pattern. One is that it guides you away from the idea of multiple slice reducers independently responding to the same action. Nothing about "ducks" prevents you from having multiple reducers respond, but having everything in one file somewhat suggests that it's all self-contained and not as likely to interact with other parts of the system. There's also some aspects of dependency chains and imports involved - if any other part of the system wants to import action creators from a duck, it will kind of drag along the reducer logic in the process. The reducers may not actually get imported elsewhere, but there's a dependency on that one file. If that doesn't bother you, feel free to use "ducks".

我可以立即想到四种方法来让两个模块的 reducer 响应相同的操作:

  1. 让模块 A 直接从模块 B 的“duck”导入操作常量
  2. 在单独的文件中定义操作常量,以便模块 A 从“moduleB/constants”导入 * 作为类型
  3. 复制操作类型字符串,以便模块 A 实际上不会从模块 B 导入任何内容
  4. 使用单独的副作用库(例如 saga 或 observable)以某种方式将行为粘合在一起。

我个人建议不要过多担心跨“模块”导入或依赖项,除非您真的试图将应用程序的不同部分完全封装在其他所有内容中。

关于javascript - React-Redux跨模块通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46533617/

相关文章:

javascript - KineticJs 不同 Angular 旋转

javascript - 在 VSCode 的 NodeJs 调试器中使用 "esm"

javascript - 'npm start' 命令不执行任何操作

c# - 将键/值匿名对象作为参数传递

javascript - 在嵌套原型(prototype)子对象中使用 'this'

javascript - 使用第三方库和 React js 出现错误

javascript - 如何从多个对象中查找字符串?

javascript - 使用react-dnd在形状的边缘拖放?

css - 在 MVC 架构中存储网站的样式表

javascript - Sailsjs websockets 文档去哪儿了?