简体   繁体   English

使用ReactJS中的逆向数据流,让孩子与父母进行交流的好方法是什么?

[英]What is the good way for child to parent communication using inverse data flow in ReactJS?

I was wondering something about the reverse data flow in a React app. 我想知道有关React应用程序中反向数据流的一些信息。 Considering this question: data flow in react application and this article http://facebook.github.io/react/docs/thinking-in-react.html 考虑以下问题: React应用程序中的数据流和本文http://facebook.github.io/react/docs/thinking-in-react.html

We can see that the "normal" way to communicate from child to parent component is using callback passing through this.props.myCallback. 我们可以看到,从子组件到父组件进行通信的“正常”方式是使用通过this.props.myCallback传递的回调。 (the StackOverflow article is a good example) (StackOverflow文章是一个很好的例子)

My questions are: 我的问题是:

  • I understand the concept but what if we have deeper components? 我理解这个概念,但是如果我们有更深入的组件,该怎么办? We would have to pass this callback to every component between the top parent component who hold the state and the actual triggering component. 我们必须将此回调传递给持有状态的顶级父组件与实际触发组件之间的每个组件。 And if there is 3 to 4 components between them, I would have to pass the callback using this.props in each component. 如果它们之间有3到4个组件,则必须在每个组件中使用this.props传递回调。
  • Why not using an Event Emitter? 为什么不使用事件发射器? I could send an event from the deep child component and then listen to this event in my top state parent component. 我可以从深度子组件发送事件,然后在顶级状态父组件中侦听此事件。 This way we could avoid all the code between these two. 这样我们可以避免这两者之间的所有代码。

Please tell me what are your thoughts about this! 请告诉我您对此有何想法!

I learnt the hard way that it is a good practice to keep as much logic as possible in the highest level in the hierarchy of your components. 我学到了一种很难的方法,那就是在您的组件层次结构的最高层次上保持尽可能多的逻辑是一种好习惯。 Dan Abramov well expressed this idea in the article Smart and Dumb Components , where Smart Components are those that hold the logic, whereas Dumb Components are just meant to display. 丹·阿布拉莫夫(Dan Abramov)在“ 智能和哑巴组件 ”一文中很好地表达了这一想法,其中智能组件是那些持有逻辑的组件,而哑巴组件只是用于显示。

So yes, the callback mechanism works well when you simply want to update the father's state, or you want the father to do an action whose logic you do not want to belong to the child. 因此,是的,当您仅想更新父亲的状态,或者希望父亲执行其逻辑不想属于孩子的动作时,回调机制就可以很好地工作。

When you have anything slightly more complicated than this I would suggest you go with a Flux-ish architecture of your taste. 当您有任何比这更复杂的事情时,我建议您使用自己喜欢的Flux-ish体系结构。 Flux indeed uses node's EventEmitter to communicate with the components. Flux实际上使用节点的EventEmitter与组件进行通信。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM