How can I create shared state for HOC?

2019-04-13 08:06发布

问题:

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.