简体   繁体   中英

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 . 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. One tag is owned by an <Entries> component, and the other is owned by a <Tags> component.

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. What's the best way to do this? Should all <Tags> have the same root component? 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

  • You should keep the state in a common owner component of <Tags> and <Entries> .
  • You should pass a change handler from the state owner component to the <Tag> component
  • When the tag changes the state owner will update <Tag> s in both <Tags> and <Entries>

  • Reading this should give you a lot of insight: http://facebook.github.io/react/docs/thinking-in-react.html

2- Pure Flux way

  • If your application is a little more complex than what you have told you can go with flux architecture.
  • To do this you should have actions,dispatchers and stores implemented in your application.
  • 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. Then all the components updates themselves with the new state.

  • You can find about flux here: http://facebook.github.io/flux/docs/overview.html

id's should generally be unique within an html document. The best solution would be to change your id's to classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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