this.context返回一个空对象

时间:2019-04-08 22:16:42

标签: javascript reactjs callback react-redux react-dom

我是在生产应用程序中首次设置ContextApi,希望以此替换当前对应用程序配置的处理。我遵循了官方文档,并咨询了其他人使用该API时遇到的类似问题,并使其达到可以在执行Config.Consumer和渲染函数中的回调时正确配置的地步。但是,我无法获得this.context返回除空对象之外的任何东西。

理想情况下,我会在生命周期方法中使用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;

当前运行于:

  • 反应16.8.6(希望看到有关circuit回代码的错误消息,但 没有收到任何警告)
  • React-DOM 16.7.0
  • React-Redux 6.0.1

2 个答案:

答案 0 :(得分:1)

问题在于import os import zipfile from selenium import webdriver PROXY_HOST = '192.168.3.2' # rotating proxy or host PROXY_PORT = 8080 # port PROXY_USER = 'proxy-user' # username PROXY_PASS = 'proxy-password' # password manifest_json = """ { "version": "1.0.0", "manifest_version": 2, "name": "Chrome Proxy", "permissions": [ "proxy", "tabs", "unlimitedStorage", "storage", "<all_urls>", "webRequest", "webRequestBlocking" ], "background": { "scripts": ["background.js"] }, "minimum_chrome_version":"22.0.0" } """ background_js = """ var config = { mode: "fixed_servers", rules: { singleProxy: { scheme: "http", host: "%s", port: parseInt(%s) }, bypassList: ["localhost"] } }; chrome.proxy.settings.set({value: config, scope: "regular"}, function() {}); function callbackFn(details) { return { authCredentials: { username: "%s", password: "%s" } }; } chrome.webRequest.onAuthRequired.addListener( callbackFn, {urls: ["<all_urls>"]}, ['blocking'] ); """ % (PROXY_HOST, PROXY_PORT, PROXY_USER, PROXY_PASS) def get_chromedriver(use_proxy=False, user_agent=None): path = os.path.dirname(os.path.abspath(__file__)) chrome_options = webdriver.ChromeOptions() if use_proxy: pluginfile = 'proxy_auth_plugin.zip' with zipfile.ZipFile(pluginfile, 'w') as zp: zp.writestr("manifest.json", manifest_json) zp.writestr("background.js", background_js) chrome_options.add_extension(pluginfile) if user_agent: chrome_options.add_argument('--user-agent=%s' % user_agent) driver = webdriver.Chrome( os.path.join(path, 'chromedriver'), chrome_options=chrome_options) return driver def main(): driver = get_chromedriver(use_proxy=True) #driver.get('https://www.google.com/search?q=my+ip+address') driver.get('https://httpbin.org/ip') if __name__ == '__main__': main() 没有引用使用someNestedComponent的类:

this.context

它是指包装原始类的功能组件,因为它是用someNestedComponent.contextType = Config; 装饰器装饰的,它是以下语句的语法糖:

@connect

它应该是:

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

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

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

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

答案 1 :(得分:1)

您没有使用consumer来获取值

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

相关问题