传播Redux动作在mapDispatchToProps中不起作用

时间:2019-03-11 07:12:02

标签: javascript reactjs redux react-redux

我的mapDispatchToProps的工作方式如下:

const mapDispatchToProps = dispatch => ({
  getCourts: () => dispatch(courtActions.getCourts()),
  selectStyle: style => dispatch(courtActions.selectStyle(style)),
  selectPoint: index => dispatch(courtActions.selectPoint(index)),
  sortPoints: sort => dispatch(courtActions.sortPoints(sort))
});

我想这样写:

const mapDispatchToProps = dispatch => ({
      ...courtActions,
});

但是当我这样做时,我的所有动作都不起作用(它们不会被派遣)。我敢肯定这是显而易见的。但是,这是怎么回事?

这是操作文件:

export const getCourts = () => dispatch =>
  axios
    .get("/courts")
    .then(response => dispatch({ type: GET_COURTS, payload: response.data }));

export const selectStyle = style => ({ type: SELECT_STYLE, payload: style });

export const sortPoints = type => ({ type: SORT_POINTS, payload: type });

export const selectPoint = index => ({ type: SELECT_POINT, payload: index });

export default {
  getCourts,
  selectStyle,
  sortPoints,
  selectPoint
};

2 个答案:

答案 0 :(得分:4)

mapDispatchToProps也带有一个对象,您可以使用该对象,而不必将函数定义为mapDispatchToProps,而该函数需要返回使用调度的函数。

根据文档:

  

如果传递了一个对象,则假定该对象内部的每个函数都是一个   Redux动作创建者。具有相同功能名称但具有   每个动作创建者都包裹在调度调用中,因此他们可能是   直接调用,将​​合并到组件的道具中。

示例

const mapDispatchToProps = courtActions;

或者您可以简单地将courtActions作为第二个参数进行传递

connect(mapStateToProps, courtActions)(MyComponent);

答案 1 :(得分:0)

根据我的理解,

mapDispatchToProps是一个函数,该函数将dispatch作为参数,并且多数民众赞成在一个调度程序中,将消息分发给减速器。您不能像想要的那样使用。