How can I create shared state for HOC?

断了今生、忘了曾经 提交于 2019-12-06 12:49:26

问题


I have created LoadBookHOC which is wrapped with BookDetails and BookSummary component.

LoadBookHOC.js

const LoadBookHOC = InnerComponent => class LoadBook extends React.Component {
    constructor(){
       super();
       this.state={
          book: []
       };
    }

    set= obj => this.setState(obj);

    render(){
      return(
         <InnerComponent 
            {...this.props} 
            hocState={this.state} 
            hocSetState={this.set}
         />
      );
    }

}

BookDetails.js

this.hocSetState({book: <new data>});

BookSummary.js

this.hocSetState({book: <new data>});

Whenever this.props.hocState.book called in BookDetails or BookSummary, I need to get the same data. I mean all the InnerComponent should get the same update. Is there any other way instead of redux (makes use to write lots of code)?

update: How can I make this HOC acting like a provider or context or shared state? which one is suitable for this scenario?


回答1:


HOC is not for sharing state , but sharing functionality. If you are having two instances for eg: <BookDetails/> and <BookSummary/> in same page , both enhanced with same HOC, there will be two instances of book array. So updating in one component wont be visible to other one.

For sharing state you should as you said use Redux or store state in common Parent component.



来源:https://stackoverflow.com/questions/49707746/how-can-i-create-shared-state-for-hoc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!