我是在生产应用程序中首次设置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;
当前运行于:
React 16.8.6(希望看到有关circuit回代码的错误消息,但未收到任何警告)
React-DOM 16.7.0
React-Redux 6.0.1
炎炎设计
相关分类