我目前正在发送用户分析跟踪事件,而不是像这样的临时事件:
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中。
可以做一些类似的事情:
import React from 'react';
import withTracking from '../hoc/withTracking';
class NamePage extends Component {
render() {
...
}
}
export default withTracking(NamePage, {
eventTitle: 'View Page: NamePage',
});这个是可能的吗?我的设置正确吗?有没有更好的方法来添加用于此目的的HOC?
谢谢
发布于 2017-12-23 11:18:14
看看lifecycle method吧。它接受object和你想要的所有生命周期方法,并返回一个将方法添加到组件的HOC。
我建议您稍微修改一下withTracking接口。您可以通过将withTracking设置为带有eventTitle参数的工厂函数来使其成为可组合的。
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)https://stackoverflow.com/questions/47949249
复制相似问题