简体   繁体   中英

How to make generic react components using Redux connect decorator?

I have a project with many components like:

 @connect((store) => {
  return {
    metrics: store.billing_reports_metrics.billing_reports_metrics,
    startDateOnLoad: store.billing_reports_metrics.startDateAutohealing,
    endDateOnLoad: store.billing_reports_metrics.endDateAutohealing,
    metricsFetched: store.billing_reports_metrics.fetched,
    errorMsg: store.billing_reports_metrics.error,
    fetching: store.billing_reports_metrics.fetching
  };
})
class BillingReportsController extends MyComponent {
  constructor(props){
      let custom_methods = ['refreshTableOnDateChange', 'renderAllTables'];
      super(props, custom_methods);
      this.props.dispatch({type: "SET_BILLING_REPORTS_START_DATE", payload: moment().tz('US/Eastern').subtract(1, 'hours')})
      this.props.dispatch({type: "SET_BILLING_REPORTS_END_DATE", payload: moment().tz('US/Eastern')})
  }

  componentWillMount() {
    this.props.dispatch(fetchBillingReportsMetrics(this.props.startDateOnLoad,this.props.endDateOnLoad))
  }

I'd like to make this type of controller generic, which would be easy if it was a regular component you could pass props. Problem is the props get passed in through a decorator, and each of these components are in separate files

How can I make this generic and do the same thing for types of reports besides billing_reports across my app?

You could try using custom Higher-order Component

That way, you should be able to pass name of the state property of your liking to the decorator ('billing_reports' in example) or other props as needed.

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