在 React-Redux 中验证 'Container Component' 中的触发事件

Validate Fired Events in 'Container Component' in React-Redux

我正在尝试采用在 'Container Component'(也称为智能组件)中执行所有操作然后将数据传递到 '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' 函数?

分离 "Containers" 和 "Presentational Components" 的主要好处之一是处理其中特定组件的所有逻辑。也就是说,您可以定义一个更改状态的操作,并且仅在有效时触发它。

Class PresentationalComponent extends React.Component {
  ...
  onEventHandler() {
    if ( eventIsValid ) this.props.changeState();
  }
  ...
}

并且:

Class ContainerComponent extends React.Component {
  ...
  render() {
    <PresentationalComponent changeState={actions.changeState} />
  }
}

connect 允许第三个参数称为 mergeProps:

connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])

mergeProps 是一个函数,它将从您的 mapStateToPropsmapDispatchToProps 和提供给您的组件的道具中接收结果。它允许您全部使用它们来操作和 return 应应用于您的组件的最终道具。这可能是一个机会,可以根据您的状态使用额外的验证逻辑来​​装饰您的动作创建者。您可以随心所欲,return将一组全新的道具应用于您的组件。

例如,使用您描述的案例:

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());
};