我正在尝试采用在“容器组件”(又称智能组件)中执行所有操作的理念。然后只是将数据传递给'Presentation Components'。
我暂时陷入困境,我需要在将动作发送到Reducer
之前验证用户操作(触发事件)。我想这样做的方法是在'mapDispatchToProps'中验证函数中的事件。
代码如下所示:
const mapStateToProps = ({ oneState, twoState }) => {
return({
oneState : oneState,
twoState : twoState
});
};
const mapDispatchToProps = ( dispatch ) => {
return({
dispatchOneAction : () => {
// do the validation here. The validation requires access to
// the 'oneState' obj above in the 'mapStateToProps'
}
});
};
const C_Element = connect( mapStateToProps, mapDispatchToProps )( Ele );
我的问题是,有可能吗?或者我必须在presentation component
下游执行验证,然后调用'dispatchOneAction'函数吗?
答案 0 :(得分:3)
connect
允许第三个名为mergeProps
的参数:
connect([mapStateToProps],[mapDispatchToProps],[mergeProps], [选项])
mergeProps
是一项功能,可以从您的mapStateToProps
,mapDispatchToProps
以及提供给您的组件的道具中获得结果。它允许您全部使用它们来操纵和返回应该应用于组件的最终道具。这可能是一个根据您的状态使用其他验证逻辑来装饰您的动作创建者的机会。你可以做任何你喜欢的事情,返回一组全新的道具来应用于你的组件。
例如,使用您描述的案例:
const mapStateToProps = ({ oneState, twoState }) => {
return({
oneState : oneState,
twoState : twoState
});
};
const mapDispatchToProps = ( dispatch ) => {
return bindActionCreators({
successAction: MyActions.successAction,
failAction: MyActions.failAction
}, dispatch);
};
const mergeProps = (stateProps, dispatchProps, ownProps) => {
const { oneState, twoState } = stateProps;
const { successAction, failAction } = dispatchProps;
const validatorAction = () => {
if (oneState && twoState) {
successAction();
} else {
failAction();
}
}
return Object.assign(
{},
stateProps,
// We are providing new actions props
{ validatorAction },
ownProps
);
}
const C_Element = connect( mapStateToProps, mapDispatchToProps, mergeProps)( Ele);
有关详细信息,请参阅official react-redux
docs。
另一种方法是使用基于redux-thunk
的操作。这允许您在操作创建者中封装逻辑,并且可以访问状态。您还可以在thunk
操作中启动更多操作。
例如:
function validatingAction() {
return (dispatch, getState) => {
const { stateOne, stateTwo } = getState();
if (stateOne && stateTwo) {
dispatch(successAction());
}
dispatch(failedAction());
};
答案 1 :(得分:0)
分离容器的主要好处之一"和#34;演示组件"是处理其中特定组件的所有逻辑。也就是说,您可以定义一个更改状态的操作,只在有效时触发它。
Class PresentationalComponent extends React.Component {
...
onEventHandler() {
if ( eventIsValid ) this.props.changeState();
}
...
}
和
Class ContainerComponent extends React.Component {
...
render() {
<PresentationalComponent changeState={actions.changeState} />
}
}