我的目标是在两个组件subscription
和Trial
之间共享一个名为SubscribeModal
的对象,但是我在执行此操作时遇到了问题,似乎subscription
对象是undefined
组件上下文中的SubscribeModal
。我不确定为什么会这样。
我现在的理论是,SubscribeModal
仅在用户单击启动模式的UI中的按钮时才得到评估,因此redux存储最终变成了怪异状态。
这是减速器:
import {SET_SUBSCRIPTION}from 'app/const/subscription';
const initialState = {
subscription: {}
};
export default function subscriptionReducer(state = initialState, action) {
switch (action.type) {
case SET_SUBSCRIPTION:
return Object.assign({}, state, action.subscription);
default:
return state
}
}
这是动作:
import {SET_SUBSCRIPTION}from 'app/const/subscription';
function setSubscription(subscription) {
return (dispatch) => {
return dispatch({
type: SET_SUBSCRIPTION,
subscription: subscription
})
}
}
export { setSubscription };
这里是Trial
组件:
@connect(null, { fetchSubscription, setSubscription })
export default class Trial extends Component {
static propTypes = {
fetchBilling: func.isRequired,
setSubscription: func.isRequired,
}
componentDidMount() {
this.checkForSubscription();
}
async checkForSubscription() {
const { fetchBilling, setSubscription } = this.props;
try {
const result = await fetchBilling();
if(result.subscription) {
setSubscription(result.subscription);
}
} catch(e) {
// Not sure if I should do something here..
}
}
render() {
// render some subscription info
}
}
这里是SubscribeModal
组件-单击用户界面中的按钮并弹出模式时,将调用以下代码:
export default features => WrappedType => {
function SubscribeModal(props) {
const { legacySubData, subscription ...other } = props;
if (!subscription) { // this is where the issue occurs, subscription is undefined
return <UpgradeSub {...other} />;
}
return <WrappedType {...other} />;
}
SubscribeOnlyModal.displayName = `SubscribeModal(${getDisplayName(WrappedType)})`;
SubscribeOnlyModal.propTypes = {
legacySubData: PropTypes.object,
subscription: PropTypes.object
};
return connect(({ legacySubData, subscription }) => ({ legacySubData, subscription }))(SubscribeModal);
};
在上面,subscription
是未定义的,我不确定为什么。我认为这可能是由于我正在调用async checkForSubscription
的{{1}}中的Trial
函数引起的。但是我不确定。同样,setSubscription
看起来也不像普通的组件类……它是通过其“父”组件中的装饰器来调用的,例如SubscribeModal
。对于@SubscribeModal()
未定义的原因,不确定是否可能是这些因素。