this.context 返回空对象

this.context returning an empty object

我第一次在生产应用程序中设置 ContextApi,希望用它替换我们当前对应用程序配置的处理。我遵循了官方文档并咨询了其他人在使用 API 时遇到的类似问题,并且在我执行 Config.Consumer 和回调时能够正确配置渲染函数。但是,除了一个空对象之外,我不能得到 this.context 到 return 任何东西。

理想情况下,我会在生命周期方法中使用 this.context 以避免回调地狱,因此我们将不胜感激。我已经仔细检查了我的 React 版本并且我正在设置 contextType。下面是代码的表示

config.js

import { createContext } from "react";
export default createContext();

index.js

import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { Router, browserHistory } from "react-router";
import { syncHistoryWithStore } from "react-router-redux";
import Config from "../somePath/config";
// more imports


function init() {
  const config = getConfig();
  const routes = getRoutes(config);
  const history = syncHistoryWithStore(browserHistory, appStore);

  ReactDOM.render(
    <Provider store={appStore}>
      <Config.Provider value={config}>
        <Router history={history} routes={routes} />
      </Config.Provider>
    </Provider>,
    document.getElementById("app")
  );
}
init();

someNestedComponent.js

import React, { Component } from "react";
import { connect } from "react-redux";
import Config from "../somePath/config";

@connect(
  state => ({
    someState: state.someState,
  })
)
class someNestedComponent extends Component {
  componentDidMount() {
    console.log(this.context);
  }

  render() {
    return (...someJSX);
  }
}
someNestedComponent.contextType = Config;

export default someNestedComponent;

目前 运行 于:

问题是 someNestedComponent 没有引用使用 this.context 的 class:

someNestedComponent.contextType = Config;

指的是把原来的class包裹起来的功能组件,因为它被@connect装饰器装饰了,它是语法糖:

const someNestedComponent = connect(...)(class someNestedComponent extends Component {
  ...    
});
someNestedComponent.contextType = Config;

相反,它应该是:

@connect(...)
class someNestedComponent extends Component {
  static contextType = Config;

  componentDidMount() {
    console.log(this.context);
  }
  ...
}

上下文没有回调地狱问题API;这可以使用与 React Redux 中使用的相同的高阶组件模式方便地解决,并且还可以从装饰器语法中受益:

const withConfig = Comp => props => (
  <Config.Consumer>{config => <Comp config={config} {...props} />}</Config.Consumer>
);
@connect(...)
@withConfig
class someNestedComponent extends Component {
  componentDidMount() {
    console.log(this.props.config);
  }
  ...
}

您没有使用 consumer 获取值

参考:https://reactjs.org/docs/context.html#contextconsumer