首页 > 解决方案 > 包含通过使用 Redux 的渲染道具子项中的更改重新渲染的提供程序

问题描述

我有类似的东西:

const higherOrderComponent = (WrappedComponent) => {
  return class extends React.Component {
    render() {
      <CustomProvider
        render={({isLoading, playNote, playNoteAtTime, stopNote}) => {

            return <WrappedComponent />;
        }
      />
  }
};

我的应用程序中有一个更高的 redux 商店,当用户与“WrappedComponent”交互时,它会向商店发送一个动作,这会导致“higherOrderComponent”重新渲染。

这在以前不是问题,因为我一直偏爱无状态组件,并且让新状态在状态更改时通过整个应用程序进行清洗,没有性能问题。

不过,自定义提供程序正在异步加载一些文件,所以现在有一个值得注意的问题。

解决方案的一个想法是在“higherOrderComponent”级别的组件中引入状态。首次加载组件时,我将从 store 道具中填充状态。

然后我可以保存并调度操作,以便稍后在适当的时候更新商店。

我不确定我是否已经使用上述方法创建了一个反模式(我同时使用带有“渲染道具”的高阶组件)。

或者是否有人可以推荐更好的解决方案?

编辑 我被要求展示 CustomProvider 正在做什么,所以我在这里添加了一部分:

class SampleProvider extends React.Component {
  static propTypes = {
    instrumentNames: PropTypes.array.isRequired,
    audioContext: PropTypes.instanceOf(window.AudioContext),
    render: PropTypes.func
  };

  static defaultProps = {
    currentInstrument: 'mooga'
  };

  constructor(props) {
    super(props);

    this.playNote = this.playNote.bind(this);
    this.state = {
      activeAudioNodes: {},
      instrument: null
    };
  }

  componentDidMount() {
    sampleLoader.init(this.props.audioContext, sampleFilePaths).then(loadedSamplesBuffers => {
      this.samplesBuffers = loadedSamplesBuffers;
      console.log('End: loading samples');
    });
  }

  playNote = midiNumber => {

    let play = samplePlayer(this.props.audioContext, this.props.mainOutput, this.samplesBuffers);

    play(midiNumber, 0, null, null, this.props.currentInstrument);

  };

标签: reactjsreduxreact-redux

解决方案


推荐阅读