this.context返回一个空对象

问题描述 投票:1回答:2

我正在生产应用程序中首次设置ContextApi,希望用它替换我们当前对app配置的处理。我已经关注了官方文档并咨询了其他人在使用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;

目前正在运行:

  • React 16.8.6(hopi查看有关迂回代码的错误消息,但未收到任何警告)
  • React-DOM 16.7.0
  • React-Redux 6.0.1
javascript reactjs callback react-redux react-dom
2个回答
1
投票

问题是someNestedComponent没有提到使用this.context的类:

someNestedComponent.contextType = Config;

它指的是包装原始类的功能组件,因为它是用@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);
  }
  ...
}

1
投票

您没有使用consumer来获取值

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

© www.soinside.com 2019 - 2024. All rights reserved.