在组件输入中传递的值更改了父级 [英] Value passed in component input changing parent

查看:57
本文介绍了在组件输入中传递的值更改了父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,组件中的Input字段应该是单向的(对于子级是父级的).但是,我有一个值传递给Input,然后在组件中对其进行修改,但我也注意到它在父级中也发生了变化.这对我来说很有意义,因为对象是通过引用传递的,但是我猜测这意味着Angular设置的整个单向绑定"只是一个范例,不是严格的吗? Angular没有任何办法强制执行单向绑定?

As I understand it, the Input fields in a component are supposed to be one directional (parent to child). However, I have a value I'm passing into an Input and then modifying it in the component, but I'm noticing it changes in the parent as well. That makes some sense to me, as objects are passed by reference, but I'm guessing that means that the whole "one way binding" thing Angular sets is just a paradigm, not strict? Angular does nothing under the hood to enforce one way binding?

基本上,我在做

<session-form [values]="session"></session-form>

session-form组件中,我将session.start从unixtimestamp更改为Moment对象.但随后我在父级中注意到,session.start也是Moment对象.

In the session-form component, I change session.start from a unixtimestamp to a Moment object. But I then notice in the parent, session.start is also a Moment object.

使用这样的数据是否存在范例?一旦设置了输入值,是否应该将输入值复制到严格限制于该组件的变量中?

Is there a paradigm for using data like this? Should I be copying input values to a variable scoped strictly to the component once it's set?

推荐答案

查看智能/哑巴(容器/外观)组件体系结构.

Look into the smart/dumb (container/presentational) component architecture.

基本上,这个想法是智能组件包含您的应用程序状态或与包含该状态的服务进行对话.愚蠢的组件只是呈现@Input提供给它的数据.智能组件将状态传递给哑​​组件.

Basically the idea is that smart components contain the state of your app or talk to a service that contains the state. The dumb components just render the data given to it from the @Input. The smart components pass the state to the dumb component.

您可以使用事件发射器告诉智能组件更新数据,而不是直接更新哑组件中的数据.这样,您就可以实现单向数据流.

Instead of directly updating the data in the dumb component you use an event emitter to tell the smart component to update the data. This way you have the one way data flow.

更多信息在这里: http://blog.angular-university.io/angular-2-smart-components-vs-presentation-components-whats-the-difference-when-to-use-each-and-why/

这篇关于在组件输入中传递的值更改了父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆