2017-12-23 6 views
1

나는 현재 지금과 같은 HOC없이 이벤트를 추적하는 사용자 분석을 보내고있다 :Recompose HOC를 User Analytics에 쓰는 방법은 무엇입니까?

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 %가, 내가이 다시 컴포지션 내 페이지를 포장해야 것을 배우고을 감안할 때 HOC.

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

class NamePage extends Component { 

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

이게 가능 :

같은 일을 할 수 있습니까? 내가 이것을 올바르게 설정하고 있습니까? 이 목적을 위해 HOC를 추가하는 더 좋은 방법이 있습니까?

답변

2

lifecycle method 한 번 봐 주셔서 감사합니다. 원하는 모든 라이프 사이클 메소드로 객체를 취하고 메소드에 컴포넌트를 추가하는 HOC를 반환합니다.

Tracking 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) 
+1

감사합니다. 매우 도움이됩니다. 'this.context.mixpanel.track'은 NamePage 구성 요소에서 사용할 수 있지만 HOC에서는 사용할 수 없습니다. - HOC에 전달해야합니까? – AnnaSm

+0

이상한, 내가 왜 묻는 지 오류가 발생했습니다 : Uncaught TypeError : 정의되지 않은 'track'속성을 읽을 수 없습니다 at Lifecycle.componentDidMount' – AnnaSm

+0

아마도 문맥을 설정하고 있기 때문에 고장났습니다. 이상적으로 NamePage.contextTypes = {mixpanel ...}은 HOC에서 이동할 수 있으므로 모든 React.Compoment에서 반복되지 않습니다. NamePage.contextTypes = { mixpanel : PropTypes.object.isRequired } – AnnaSm