How can I create shared state for HOC?

2019-04-13 08:09发布

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条回答
做自己的国王
2楼-- · 2019-04-13 08:18

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.

查看更多
登录 后发表回答