getDefaultProps中的缓存道具是React中的反模式吗?

shi*_*anb 8 javascript reactjs react-jsx

我正在编写一个复杂的反应应用程序并使用Cortex作为我的中心模型.皮质的哲学是它包装你的数据和更改数据,从根调用完整的重新渲染.这非常有用,尤其是当您有非分层视图更改状态并影响另一个时.

我面临的问题是在重新渲染时保持状态/道具.例如,我有一个特定的层次结构,如下所示:

<Page>
  <EditorCard>
     <Editor/>
     <PublishButton/>
  </EditorCard>
</Page>
Run Code Online (Sandbox Code Playgroud)

EditorCard需要的JavaScript的情况下Editor,为了使更改Editor上单击PublishButton(我用的内外部库Editor,其公开的编辑方法).因此,Editoron 通过调用传递给它的函数ComponentDidMount将实例设置为propon EditorCard.

我的问题是,当我点击PublishButton我更改皮质对象的值,导致从根重新渲染,并为此松开道具Editor(因为组件已经安装ComponentDidMount不再被调用).

我处理这个问题的方法是缓存getDefaultProps.

EditorCard我的默认道具里面是:

  getDefaultProps: function() {
    return {
      cachedData: {},
    }
  },
Run Code Online (Sandbox Code Playgroud)

并将编辑器实例保存为 this.props.cachedData.editor = editorInstance

这可以在多次重新渲染中保存道具.

这是如何使用getDefaultProps缓存的?在通过多次重新渲染保存道具时,我打破了这个黑客的一些核心反应规则?如果是这样,你能建议一个更好的结构?

che*_*lou 6

不,getDefaultProps这意味着什么:获取默认道具,以防所有者没有将这些道具传递给您.你可以说这是一个简写a = this.props.bla || 'hello';.

话虽如此,如果我正确理解你的问题,我会看到三种方法来解决它.

  1. 在你的状态缓存,而不是.道具由父母传递,并且意图从孩子内部读取,至少在香草React中.

  2. 而不是把道具传递给你的道具componentDidMount,为什么不把它放进去componentDidUpdate

  3. ref 让你抓住实例并直接调用它的方法.