Reputation: 155
I am writing a complex react app and using Cortex as my central model. The philosophy with cortex is that it wraps your data and on changing the data, calls a complete re-render from the root. This works great especially when you have non hierarchical views changing state and affecting the other.
The issue that I am facing is maintaining states/props on re-render. For example I have a certain hierarchy which goes like this:
<Page>
<EditorCard>
<Editor/>
<PublishButton/>
</EditorCard>
</Page>
The EditorCard
needs the JavaScript instance of the Editor
in order to make changes to the Editor
on clicking the PublishButton
(I am using an external library inside Editor
which exposes methods for editing). Hence the Editor
on ComponentDidMount
sets the instance as a prop
on the EditorCard
by calling a function passed down to it.
My issue is that when I click the PublishButton
I change the value of the cortex object which causes a re-render from the root and I loose the props for that Editor
(since component is already mounted ComponentDidMount
is not called again).
The way I took care of this problem is by caching of getDefaultProps
.
Inside EditorCard
my default props are:
getDefaultProps: function() {
return {
cachedData: {},
}
},
And is saving the editor instance as this.props.cachedData.editor = editorInstance
This saves props over multiple re-renders.
Is this how getDefaultProps
caching was meant to be used? On saving props over multiple re-renders am I breaking some of the core react rules with this hack? Could you suggest a better structure if so?
Upvotes: 8
Views: 5820
Reputation: 3640
No, getDefaultProps
is what it means to be: getting the default props in case the owner hasn't passed those to you. You could say it's a shorthand for a = this.props.bla || 'hello';
.
That being said, if I'm understand your question correctly, I see three ways to solve it.
Cache that in your state instead. Props are passed by the parent and are meant to be read from, inside the child, at least in vanilla React.
Instead of putting that props passing logic in your componentDidMount
, why not put it in componentDidUpdate
?
ref
lets you grab the instance and call its methods directly.
Upvotes: 6