首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何编写一个recompose HOC to User Analytics?

如何编写一个recompose HOC to User Analytics?
EN

Stack Overflow用户
提问于 2017-12-23 10:22:54
回答 1查看 402关注 0票数 1

我目前正在发送用户分析跟踪事件,而不是像这样的临时事件:

代码语言:javascript
复制
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;

考虑到我99%的页面都需要这个跟踪函数,我正在学习,我应该将我的页面包装在recompose HOC中。

可以做一些类似的事情:

代码语言:javascript
复制
import React from 'react';
import withTracking from '../hoc/withTracking';

class NamePage extends Component {

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

这个是可能的吗?我的设置正确吗?有没有更好的方法来添加用于此目的的HOC?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-23 11:18:14

看看lifecycle method吧。它接受object和你想要的所有生命周期方法,并返回一个将方法添加到组件的HOC。

我建议您稍微修改一下withTracking接口。您可以通过将withTracking设置为带有eventTitle参数的工厂函数来使其成为可组合的。

代码语言:javascript
复制
 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)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47949249

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档