访问mapDispatchToProps中的容器道具

时间:2017-12-21 18:12:06

标签: reactjs redux react-redux

我有以下界面:

interface EditUserContainerProps
  extends RouteComponentProps<EditUserParams>,
  EditUserStateProps,
  EditUserDispatchProps { }

interface EditUserParams {
  id: number;
  history: any;
}

interface EditUserStateProps {
  isLoading: boolean;
  isSubmitting: boolean;
  userFields: UserField[];
  User: User;
}

interface EditUserDispatchProps {
  load: (id: number) => void;
  updateUser: (User: User) => any;
  parseFile: (file: File, replace: boolean) => any;
  addRecords: (records: any[]) => any;
}

我有以下mapDispatchToProps功能:

export class EditUserContainer extends React.Component<EditUserContainerProps> {
....
function mapDispatchToProps(dispatch: Dispatch<ActionTypes>, ownProps: EditUserContainerProps): EditUserDispatchProps {
  return {
    parseFile: (file: File, replace: boolean) => {
      return fileParsingsApiActions
        .parseFile(file)(dispatch)
        .then((data: any) => {
           ownProps.addRecords( data.data);
        })
    }
  };
}

export const EditUser = connect(mapStateToProps, mapDispatchToProps)(EditUserContainer);

parseFile的回调中,ownProps是将传递到我的容器中的道具。我需要访问包含addRecords的容器的 容器。

如何在mapDispatchToProps中访问容器道具?

1 个答案:

答案 0 :(得分:0)

您可能需要将mergeProps用于此类交互。它可以访问容器的所有道具。你的dispatchProps中有你的addRecords,我相信你可以从那里访问它。

const mergeProps = (stateProps, dispatchProps, ownProps) => {
  const props = Object.assign({}, ownProps, stateProps, dispatchProps)
  props.parseFile = (file: File, replace: boolean) => {
      return fileParsingsApiActions
        .parseFile(file)(dispatch)
        .then((data: any) => {
           dispatchProps.addRecords( data.data);
        })
   }

   return props;
}

从文档中: [mergeProps(stateProps, dispatchProps, ownProps): props](函数):如果指定,则传递mapStateToProps()mapDispatchToProps()和父道具的结果。从它返回的普通对象将作为props传递给包装组件。您可以指定此函数以基于props选择状态切片,或将动作创建者绑定到props中的特定变量。如果省略,默认情况下会使用Object.assign({}, ownProps, stateProps, dispatchProps)