传播 Redux 操作在 mapDispatchToProps 中不起作用 [英] Spreading Redux Actions does not work in mapDispatchToProps

查看:47
本文介绍了传播 Redux 操作在 mapDispatchToProps 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 mapDispatchToProps 是这样工作的:

My mapDispatchToProps works like this:

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

但是当我这样做时,我的任何操作都不起作用(它们不会被派遣).我确定这是显而易见的事情.但是这里发生了什么?

but when I do that none of my actions work (they dont get dispatched). I'm sure this is something obvious. But what is going on here?

这是操作文件:

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

推荐答案

mapDispatchToProps 也接受一个对象,您可以使用它来代替将函数定义为 mapDispatchToProps需要返回使用 dispatch 的函数.

mapDispatchToProps takes an object too, which you can use instead of defining a function as mapDispatchToProps which would need to return functions that use dispatch.

根据文档:

如果传递了一个对象,则假定其中的每个函数都是一个Redux 动作创建者.具有相同函数名称的对象,但具有每个动作创建者都包含在一个调度调用中,因此它们可能是直接调用,会合并到组件的props中.

If an object is passed, each function inside it is assumed to be a Redux action creator. An object with the same function names, but with every action creator wrapped into a dispatch call so they may be invoked directly, will be merged into the component’s props.

示例

const mapDispatchToProps = courtActions;

或者您可以简单地将 courtActions 作为第二个参数传递给连接

Or you can simply pass courtActions as the second parameter to connect like

connect(mapStateToProps, courtActions)(MyComponent);

这篇关于传播 Redux 操作在 mapDispatchToProps 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆