为了账号安全,请及时绑定邮箱和手机立即绑定

this.context返回一个空对象

this.context返回一个空对象

潇湘沐 2021-04-09 14:15:09
我是在生产应用程序中首次设置ContextApi,希望以此替换我们当前对应用程序配置的处理。我遵循了官方文档,并咨询了其他人使用该API时遇到的类似问题,并使其达到可以在执行Config.Consumer和渲染函数中的回调时正确配置的地步。但是,我不能使this.context返回空对象以外的任何东西。理想情况下,我将在生命周期方法中使用this.context并避免发生回调地狱,因此将不胜感激。我仔细检查了我的React版本,并设置了contextType。下面是代码的表示形式config.jsimport { createContext } from "react";export default createContext();index.jsimport 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 importsfunction 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.jsimport 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(希望看到有关circuit回代码的错误消息,但未收到任何警告)React-DOM 16.7.0React-Redux 6.0.1
查看完整描述

2 回答

?
炎炎设计

TA贡献1808条经验 获得超4个赞

问题在于,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);

  }

  ...

}


查看完整回答
反对 回复 2021-04-22
  • 2 回答
  • 0 关注
  • 260 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信