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);
}
...
}
添加回答
举报