【发布时间】:2016-10-21 09:53:06
【问题描述】:
我有使用react-redux 库的React 应用程序。它工作正常,我得到了我的store 上下文,我可以调度操作。漂亮。
现在我遇到了一个问题。我想在根组件中声明子上下文并使用它将全局函数直接传递给子组件。
export default class Root extends React.Component {
globalFunc() {
}
getChildContext() {
return {
globalFunc: this.globalFunc
};
}
render() {
return (
{ /* ChildComponent somewhere in here */ }
);
}
}
Root.childContextTypes = {
globalFunc: PropTypes.func
}
问题在于当我有来自react-redux 的@connect 装饰器时,我得到一个空对象。当我删除装饰器时,我得到了正确的上下文。为什么Redux 会删除上下文?如何解决?
@connect(mapStateToProps)
export default class ChildComponent extends React.Component {
constructor(props, context) {
super(props, context);
console.log(this.context); // EMPTY {}
}
render() {
// ...
}
}
ChildComponent.contextTypes = {
store: PropTypes.store.isRequired,
globalFunc: PropTypes.func
}
【问题讨论】:
-
在附加 contextTypes 后导出时会发生什么?例如在最后
export default ChildComponent;
标签: reactjs react-native react-redux