为什么Context不会传递给我的HOC

问题描述 投票:1回答:1

我有一个使用HOC的组件。 HOC需要this.context,但由于某种原因,没有传递this.context。我究竟做错了什么? TY

零件:

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);

import { lifecycle } from 'recompose';

export function withTracking(eventTitle) {
    return lifecycle({
        componentDidMount() {
          console.log(this.context.mixpanel) // UNDEFINED - fail-y?
        }
    });
}

export default withTracking;

如果在组件中输出,console.log将返回undefined,返回正确。

我究竟做错了什么?谢谢

javascript reactjs recompose
1个回答
1
投票

ContextTypes仅为NamePage组件指定,以便您将它与HOC一起使用,您需要在wrappedComponent实例上指定它

const WrappedNamePage = withTracking('View Page: NamePage')(NamePage);

WrappedNamePage.contextTypes = {
  mixpanel: PropTypes.object.isRequired
};

export default WrappedNamePage
© www.soinside.com 2019 - 2024. All rights reserved.