[英]How to update two different React component instances that represent the same data?
Say I've defined a <Tag>
component that has two props: id
and name
. 说我已经定义了一个具有两个道具的
<Tag>
组件: id
和name
。 My application renders this component in two different places, so I have a <Tag>
component whose id is 1
appearing twice, but whose owners are different. 我的应用程序在两个不同的位置渲染此组件,因此我有一个
<Tag>
组件,其ID为1
出现了两次,但所有者不同。 One tag is owned by an <Entries>
component, and the other is owned by a <Tags>
component. 一个标签由
<Entries>
组件拥有,另一个<Tags>
由<Tags>
组件拥有。
When a <Tag>
is clicked, I want to change its state, and I want all other <Tag>
components with the same id
to also change their state so that they match. 单击
<Tag>
,我想更改其状态,并且希望所有其他具有相同id
<Tag>
组件也更改其状态,以便它们匹配。 What's the best way to do this? 最好的方法是什么? Should all
<Tags>
have the same root component? 所有
<Tags>
是否应具有相同的根组件? I don't like that idea, because I feel like it's a brittle solution. 我不喜欢这个主意,因为我觉得这是一个脆弱的解决方案。
I think you have two options to go: 我认为您有两种选择:
1- React way 1-反应方式
<Tags>
and <Entries>
. <Tags>
和<Entries>
的公共所有者组件中。 <Tag>
component <Tag>
组件 When the tag changes the state owner will update <Tag>
s in both <Tags>
and <Entries>
标签更改时,状态所有者将同时更新
<Tags>
和<Entries>
<Tag>
。
Reading this should give you a lot of insight: http://facebook.github.io/react/docs/thinking-in-react.html 阅读此书应该会给您带来很多见识: http : //facebook.github.io/react/docs/thinking-in-react.html
2- Pure Flux way 2-纯助焊剂方式
When a <Tag>
is changed you call an action, which in turn calls a dispatcher, which is in turn listened by stores, which in turn emits a change event to components. 更改
<Tag>
后,您将调用一个操作,该操作又调用一个调度程序,而调度程序又被商店侦听,该调度程序又向组件发出一个change事件。 Then all the components updates themselves with the new state. 然后,所有组件都将自己更新为新状态。
You can find about flux here: http://facebook.github.io/flux/docs/overview.html 您可以在此处找到有关通量的信息: http : //facebook.github.io/flux/docs/overview.html
id's should generally be unique within an html document. id在html文档中通常应该是唯一的。 The best solution would be to change your id's to classes.
最好的解决方案是将您的ID更改为类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.