【问题标题】:Missing context while using @connect使用 @connect 时缺少上下文
【发布时间】:2016-10-21 09:53:06
【问题描述】:

我有使用react-redux 库的React 应用程序。它工作正常,我得到了我的store 上下文,我可以调度操作。漂亮。

现在我遇到了一个问题。我想在根组件中声明子上下文并使用它将全局函数直接传递给子组件。

export default class Root extends React.Component {
    globalFunc() {
    }

    getChildContext() {
        return {
            globalFunc: this.globalFunc
        };
    }

    render() {
        return (
            { /* ChildComponent somewhere in here */ }
        );
    }
}

Root.childContextTypes = {
    globalFunc: PropTypes.func
}

问题在于当我有来自react-redux@connect 装饰器时,我得到一个空对象。当我删除装饰器时,我得到了正确的上下文。为什么Redux 会删除上下文?如何解决?

@connect(mapStateToProps)
export default class ChildComponent extends React.Component {
    constructor(props, context) {
        super(props, context);

        console.log(this.context); // EMPTY {}
    }

    render() {
        // ...
    }
}

ChildComponent.contextTypes = {
    store: PropTypes.store.isRequired,
    globalFunc: PropTypes.func
}

【问题讨论】:

  • 在附加 contextTypes 后导出时会发生什么?例如在最后export default ChildComponent;

标签: reactjs react-native react-redux


【解决方案1】:

我遇到了类似的问题,当我对 connect() 函数使用“普通”HoC 表单而不是装饰器时,它正在解决问题。 请注意,不建议使用 Redux 的创建者所说的装饰器形式:https://stackoverflow.com/a/35642430/757461

另外,如果你真的想使用装饰器,我可以通过使用装饰器定义我的上下文来解决这个问题。类似的东西:

export function context(contextTypes, context) {
  return DecoratedComponent => {
    return class extends Component {
      static childContextTypes = contextTypes;

      getChildContext() {
        return context(this.props)
      }

      render() {
        return <DecoratedComponent {...this.props} />
      }
    }
  }
}

然后你像这样使用它:

@connect(mapStateToProps, mapDispatchToProps)
@context(contextTypes, getChildContext)

【讨论】:

    猜你喜欢
    • 2019-08-05
    • 2011-09-02
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    相关资源
    最近更新 更多