[英]What's the best way to call callbacks passed into a Redux subapp?
I'm following the Redux "subapp" pattern described here , but I'm having a little trouble figuring out the best way to call callbacks passed into the subapp, especially in response to asynchronous actions. 我遵循此处描述的Redux“子应用”模式,但是在找出调用传递到子应用中的回调的最佳方法时遇到了一些麻烦,特别是在响应异步操作时。
Here's an inelegant but working solution: https://jsfiddle.net/jochakovsky/bgx86m6j/ . 这是一个优雅但可行的解决方案: https : //jsfiddle.net/jochakovsky/bgx86m6j/ 。 I'm not a big fan of this approach - it forces me to pass the callback further down than I'd like, into ReduxSubappView
, which shouldn't have to know anything about that callback. 我不是这种方法的ReduxSubappView
-它迫使我将回调传递到比我想要的还要低的地方,传递给ReduxSubappView
,而ReduxSubappView
不必知道有关该回调的任何信息。 The most natural place to call the callback is the async action creator initialize
, but it does not have access to the props passed into ReduxSubApp
. 调用回调的最自然的地方是异步动作创建者initialize
,但是它无法访问传递给ReduxSubApp
的道具。 Also, it feels weird to compare props and nextProps - presentational components should really only be responsible for converting the current props into a UI, and not have to understand state transitions. 而且,比较props和nextProps感觉很奇怪-表示组件实际上应该只负责将当前props转换为UI,而不必了解状态转换。 Additionally, ReduxSubappView
cannot be a pure functional component with this approach. 此外,使用这种方法, ReduxSubappView
不能成为纯功能组件。
What's the best way to handle this type of situation? 处理这种情况的最佳方法是什么?
If you don't want to pass down props from the Subapp root level and you can't use redux in all Subapps, you would need a global pub/sub or something comparable to subscribe to changes. 如果您不想从Subapp根目录下传递道具, 并且不能在所有Subapps中使用redux,则需要全局pub / sub或类似的东西来订阅更改。
Here's a native approach with addEventListener
: 这是使用addEventListener
的本机方法:
// in Subapp:
document.addEventListener('initialized', function(e){console.log('app initialized')});
// Wherever the event originates from:
document.dispatchEvent(new Event('initialized'));
A dedicated library might be better, since this has the events bubbling through the DOM (for no reason really), but it should work out of the box. 专用的库可能会更好,因为它会使事件在DOM中冒泡(这是毫无原因的),但是它应该是开箱即用的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.