简体   繁体   中英

How to persist data or state across child components in react.js?

Okay, I am seeking out the best way to persist data across child components. As per my knowledge, to communicate between a parent and a child, I should pass a callback to the child component as props. Now, if I need to change the state of the parent, I just call the callback and it sets the state of the parent. Correct?

But that is not my requirement. Let's consider a scenario where I have multiple children and all of them share the same data. What I need is, if I change the state/date in any of the children, then the data change should reflect in other child components as well. Invoking the callback will only change the state of the parent, how can I update the passed props in other children along with it?

I hope that was not confusing. I am using Flux architecture in my application. I do have an alternative solution for my problem using actions and dispatcher. However, I want to know whether there is a smarter and standard way of doing it.

Just change the state of the parent, that will trigger a re-render of the parent, pass whatever props (even if they are the same) to children and they will re-render with your new state.

Whether you pass a function from parent to children, or have children emit an action via a dispatcher (which would probably be the preferred method if you're using flux anyway), the theory is the same, parent state change and pass props to children.

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