Javascript 为什么没有将上下文传递给我的HOC
我有一个组件正在使用HOC。HOC需要this.context,但由于某些原因,未传递this.context。我做错了什么?泰 组件:Javascript 为什么没有将上下文传递给我的HOC,javascript,reactjs,recompose,Javascript,Reactjs,Recompose,我有一个组件正在使用HOC。HOC需要this.context,但由于某些原因,未传递this.context。我做错了什么?泰 组件: import React, { Component } from 'react'; import withTracking from './hocs/withTracking'; class NamePage extends Component { componentDidMount() { console.log(this.context.mi
import React, { Component } from 'react';
import withTracking from './hocs/withTracking';
class NamePage extends Component {
componentDidMount() {
console.log(this.context.mixpanel) // WORKS
}
render() {
return (
...
);
}
}
NamePage.contextTypes = {
mixpanel: PropTypes.object.isRequired
};
export default withTracking('View Page: NamePage')(NamePage);
hoc
import { lifecycle } from 'recompose';
export function withTracking(eventTitle) {
return lifecycle({
componentDidMount() {
console.log(this.context.mixpanel) // UNDEFINED - fail-y?
}
});
}
export default withTracking;
console.log返回未定义,如果我在组件中输出,它将返回correct
我做错了什么?感谢ContextTypes
仅为NamePage
组件指定,为了将其用于HOC,您需要在wrappedComponent实例上指定它
const WrappedNamePage = withTracking('View Page: NamePage')(NamePage);
WrappedNamePage.contextTypes = {
mixpanel: PropTypes.object.isRequired
};
export default WrappedNamePage