访问mapDispatchToProps中的容器道具

问题描述 投票:1回答:1

我有以下接口:

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中访问容器道具?

reactjs redux react-redux
1个回答
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](Function):如果指定,则传递mapStateToProps()mapDispatchToProps()和父道具的结果。从它返回的普通对象将作为props传递给包装组件。您可以指定此函数以基于props选择状态切片,或将动作创建者绑定到props中的特定变量。如果省略它,则默认使用Object.assign({}, ownProps, stateProps, dispatchProps)

© www.soinside.com 2019 - 2024. All rights reserved.