简体   繁体   中英

Caching props in getDefaultProps an anti-pattern in React?

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?

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'; a = this.props.bla || 'hello'; .

That being said, if I'm understand your question correctly, I see three ways to solve it.

  1. 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.

  2. Instead of putting that props passing logic in your componentDidMount , why not put it in componentDidUpdate ?

  3. ref lets you grab the instance and call its methods directly.

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