[英]How to write a recompose HOC to User Analytics?
I'm currently sending user analytic tracking events without a HOC like so: 我目前正在发送没有HOC的用户分析跟踪事件,如下所示:
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. 鉴于我99%的页面都需要此跟踪功能,因此我正在学习,我应该将页面包装在重新组成的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?
是否有更好的方法为此添加HOC?
Thank you 谢谢
Take a look at lifecycle method . 看一看生命周期方法 。 It takes object with all lifecycle methods you want and returns a HOC that will add methods to the component.
它以所需的所有生命周期方法作为对象,并返回一个HOC,它将向组件添加方法。
I suggest you to change withTracking API slightly. 我建议您稍稍更改withTracking API。 You can make it composable by making withTracking a factory function with eventTitle argument.
您可以通过使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.