【问题标题】:Why is Context not being passed to my HOC为什么上下文没有被传递给我的 HOC
【发布时间】:2018-06-05 14:11:08
【问题描述】:

我有一个使用 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.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】:

    ContextTypes 仅针对 NamePage 组件指定,为了让您将其与 HOC 一起使用,您需要在 WrappedComponent 实例上指定它

    const WrappedNamePage = withTracking('View Page: NamePage')(NamePage);
    
    WrappedNamePage.contextTypes = {
      mixpanel: PropTypes.object.isRequired
    };
    
    export default WrappedNamePage
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-15
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多