Reputation: 5419
I've read up on this a bit but have not received a satisfactory answer. Granted I'm very new to React.
Suppose I have two components, Parent
and Child
. Parent
passes a property to Child
, and Child
wishes to set a state to that property, as follows:
// in child
getInitialState: function() {
return ({
filters: this.props.filters
});
}
Then, this.state.filters
gets modified through the UI, and upon clicking a "Save" button of some sort, saves the updated filters through a Flux-like model via a Store/Dispatcher up through to the Parent
, which then re-renders and propagates down the updated this.props.filters
down to Child
again. This is kind of silly, as Child
already has the updated data in its state, but whatever.
In order to check if the "Save" button should be active, I check in Child
if:
this.state.filters === this.props.filters
If they are not equal, then the state has been changed from the original default prop. Thus, the "Save" button is activated. Otherwise, the state is identical to the original default prop, and the "Save" button is disabled.
My question is, is this flow an anti-pattern? Seems like it must be.
Upvotes: 1
Views: 458
Reputation: 17743
Within your component you want to know if a value has been modified from the last known value. This approach feels quite reasonable to me. Obviously there are other ways to do this, but I don't see anything wrong with this approach.
About this: "...saves the updated filters through a Flux-like model via a Store/Dispatcher up through to the Parent." Think of it more as stepping out of the rendering flow and into a state-updating flow in your app. The one-way nature of the flux pattern can be a bit more typing, but leads to more manageable code in the long run (e.g. if more than one component needs the updated state).
You are right that the Child
already has the soon-to-be official state which will be received again from the Parent
as props
shortly. The Child
can/should render based on that new state even though it's not been saved to the server yet - this is called Optimistic Updates https://facebook.github.io/react/docs/tutorial.html#optimization-optimistic-updates.
As long as the output of the render
method doesn't change in the Child
component after the new props
are received from the Parent
, React won't tell the browser to re-render the DOM. This means that your UI renders your desired state, but does so more quickly.
Upvotes: 2