1

I'm currently sending user analytic tracking events without a HOC like so:

import React from 'react';

class NamePage extends Component {

  componentDidMount() {
    this.context.mixpanel.track('View Page: NamePage');
  }
  render() {
  ...
  }
}

NamePage.contextTypes = {
    mixpanel: PropTypes.object.isRequired
};

export default NamePage;

Given 99% of my pages will require this track function, I'm learning that, I should wrap my pages in a recompose HOC.

Can do something like:

import React from 'react';
import withTracking from '../hoc/withTracking';

class NamePage extends Component {

  render() {
  ...
  }
}
export default withTracking(NamePage, {
  eventTitle: 'View Page: NamePage',
});

Is this possible? Am I setting this up correctly? Is there a better way to add a HOC for this purpose?

Thank you

4

1 回答 1

2

看看 生命周期方法。它接受具有您想要的所有生命周期方法的对象,并返回一个 HOC,它将向组件添加方法。

我建议您稍微更改 withTracking API。您可以通过使用带有 eventTitle 参数的 withTracking 工厂函数来使其可组合。

 import React from 'react';
 import {lifecycle, compose} from recompose;

 export function withTracking(eventTitle) {
     return lifecycle({
         componentDidMount() {
             this.context.mixpanel.track(eventTitle);
         }
     });
 }

 const class NamePage extends Component {
     render(){
         ...
     }
 }

 export default withTracking('View Page: NamePage')(NamePage);

 // and now you can compose withTracking with some other HOCs if needed
 // for example:

 export default compose(
     withTracking('View Page: NamePage'),
     someAnotherHOC,
     someAnotherHOC2
 )(NamePage)
于 2017-12-23T03:18:14.313 回答