简体   繁体   English

更新所有者状态的正确方法

[英]Correct way to update owner state

I have two components, contact form, and input. 我有两个部分,联系表格和输入。

At this moment i pass onChangeEvent from contact to input as is described in many tutorials and its works fine - input update his owner state. 目前,我将onChangeEvent从联系人传递到输入,这在许多教程中都有介绍,并且它可以正常工作-输入会更新其所有者状态。

But there is way to pass 'this' from contact to input by prop, or context and then I can update owner state without passing onChangeEvent - but is this a good idea? 但是有办法将“ this”从联系人传递到prop或上下文,然后我可以更新所有者状态而无需传递onChangeEvent-但这是个好主意吗?

Is there another option to update owner state without passing onChangeEvent? 是否有另一个选项可以在不传递onChangeEvent的情况下更新所有者状态?

I believe you could technically do it, as a React component is a regular javascript object in the end, so you could pass it as a prop. 我相信您可以从技术上做到这一点,因为React组件最终是常规的javascript对象,因此您可以将其作为道具传递。

However, that's not a good idea in general, for various reasons: 但是,由于种种原因,这通常不是一个好主意:

  • It tightly couples the two components together. 它将两个组件紧密地耦合在一起。 If you ever want to reuse the input component in another place, you'll need to pass in the exact same state. 如果您想在其他地方重用输入组件,则需要传递完全相同的状态。
  • Linked to this, it allows manipulation of the internal state of one component, by another component, which is a violation of good OO design. 与此相关,它允许另一个组件操纵一个组件的内部状态,这违反了良好的OO设计。

You are right however, that things tend to become quite verbose when working like this. 没错,但是当这样工作时,事情往往变得很冗长。 They also become hard to reason about when one has more complex trees of components passing props and change handlers between them. 当人们拥有更复杂的组件树来传递道具并在它们之间更改处理程序时,它们也变得难以推理。

One solution to the problem, is employing the Flux design pattern, and namely it's Redux implementation. 解决该问题的一种方法是采用Flux设计模式,即Redux实现。

In Redux one has a single piece of global state, a plain object, of which components see pieces (sub objects). 在Redux中,只有一个全局状态,即一个普通对象,其中的各个组件可见各个部分(子对象)。 Components receive this state as props, and just render from it in a simple fashion. 组件将这种状态作为道具接收,并以简单的方式从中进行渲染。 There's a set of actions which transform this state, and any component can issue such an action, as a result of user interaction. 有一组动作可以转换此状态,并且由于用户交互,任何组件都可以发出这样的动作。 There's still the concept of "state", but it is reserved for truly local things, such as the state of a form before pressing the save button etc. 仍然存在“状态”的概念,但是它保留用于真正的本地事物,例如按下保存按钮之前的表单状态等。

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

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