简体   繁体   中英

Fetch data using React HOC(Higher Order Component), Redux and pass props

I want to create a HOC that would allow me to call methods which will fetch data from backend and display a loader mask if they're loading. The trick is that I want to be able to pass different actions for different components.

So I'd like to call it like that:

export default withPage({
  getLoadingStatus: getStatus,
  actionOnLoad: booksActions.getAllBooksRequest
})(ShareABookContainer);

As I'm passing some props there I defined my withPage.js like below:

const withPage = ({
  actionOnLoad,
  getLoadingStatus
}) => WrappedComponent => () => {
  return (
    <PageContainer
      getLoadingStatus={getLoadingStatus}
      wrappedComponent={WrappedComponent}
      actionOnLoad={actionOnLoad}
    />
  );
};

export default withPage;

PageContainer.js is the most common container, so:

const PageContainer = props => <PageComponent {...props} />;


const mapStateToProps = (state, ownProps) => ({
  ...
});

const mapDispatchToProps = (dispatch, ownProps) => {
...
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PageContainer);

And PageComponent is a common Component as well:

class PageComponent extends Component {
  componentDidMount() {
   ...
  }

  render() { return <this.props.wrappedComponent />;
  }
}

export default PageComponent;

What happens is that nothing gets rendered and if I console.log wrappedComponent I receive:

WrappedComponent ƒ a(e,t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,a);var r=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super()…

When I'm passing some div, eg test instead of everything works fine, but what I need is for passed component to be rendered.

I have no idea what I'm doing wrong and examples in the Internet are not helping either. I wasn't able to find an example for a situation like mine (so passing props to HOC and using Redux there, it's either one or the other). I'd be very grateful for any thoughts/suggestions/answers.

Try simpler:

return (
  <PageContainer
    getLoadingStatus={getLoadingStatus}
    actionOnLoad={actionOnLoad} >
    <WrappedComponent />
  </PageContainer>
);

BTW, react rather 'doesn't like' <this.props.wrappedComponent /> No errors??

When needed dynamic components I probably used sth like:

const Wrapped = this.props.wrappedComponent;
render () { return <Wrapped /> }

Var name had to be uppercased .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM