简体   繁体   English

this.context返回一个空对象

[英]this.context returning an empty object

I'm setting up ContextApi for the first time in a production app, hoping to replace our current handling of our app configs with it. 我是在生产应用程序中首次设置ContextApi,希望以此替换我们当前对应用程序配置的处理。 I've followed the official docs and consulted with similar issues other people are experiencing with the API, and gotten it to a point where I am able to correctly the config when I do Config.Consumer and a callback in render functions. 我遵循了官方文档,并咨询了其他人使用该API时遇到的类似问题,并使其达到可以在执行Config.Consumer和渲染函数中的回调时正确配置的地步。 However, I cannot get this.context to return anything other than an empty object. 但是,我不能使this.context返回空对象以外的任何东西。

Ideally, I would use this.context in lifecycle methods and to avoid callback hell, so help would be appreciated. 理想情况下,我将在生命周期方法中使用this.context并避免发生回调地狱,因此将不胜感激。 I've double checked my React version and that I'm setting the contextType. 我仔细检查了我的React版本,并设置了contextType。 Below is a representation of the code 下面是代码的表示形式

config.js config.js

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

index.js 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 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;

Currently running on: 当前运行于:

  • React 16.8.6 (hopi to see error messages about circuitous code but didn't get any warnings) React 16.8.6(希望看到有关circuit回代码的错误消息,但未收到任何警告)
  • React-DOM 16.7.0 React-DOM 16.7.0
  • React-Redux 6.0.1 React-Redux 6.0.1

The problem is that someNestedComponent doesn't refer to the class where this.context is used: 问题是someNestedComponent没有引用使用this.context的类:

someNestedComponent.contextType = Config;

It refers to functional component that wraps original class because it was decorated with @connect decorator, it is syntactic sugar for: 它是指包装原始类的功能组件,因为它是用@connect装饰器装饰的,它是以下语法的糖:

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

Instead, it should be: 相反,它应该是:

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

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

There are no callback hell problems with context API; 上下文API没有回调地狱问题; this is conveniently solved with same higher-order component pattern as used in React Redux and can also benefit from decorator syntax: 这可以通过与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);
  }
  ...
}

You didn't use a consumer to get the values 您没有使用consumer来获取价值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM