第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

this.context返回一個空對象

this.context返回一個空對象

瀟湘沐 2021-04-09 14:15:09
我是在生產應用程序中首次設置ContextApi,希望以此替換我們當前對應用程序配置的處理。我遵循了官方文檔,并咨詢了其他人使用該API時遇到的類似問題,并使其達到可以在執(zhí)行Config.Consumer和渲染函數中的回調時正確配置的地步。但是,我不能使this.context返回空對象以外的任何東西。理想情況下,我將在生命周期方法中使用this.context并避免發(fā)生回調地獄,因此將不勝感激。我仔細檢查了我的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 關注
  • 271 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號