javascript - 传播 Redux Actions 在 mapDispatchToProps 中不起作用

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

最佳答案

mapDispatchToProps 也接受一个对象,您可以使用该对象来代替将函数定义为 mapDispatchToProps ,后者需要返回使用调度的函数。

根据文档:

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 作为第二个参数进行连接

connect(mapStateToProps, courtActions)(MyComponent);

关于javascript - 传播 Redux Actions 在 mapDispatchToProps 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55096789/

相关文章:

javascript - ReactJS:渲染请求组件列表

javascript - 从具有绝对位置的父级继承div高度

javascript - 如何在 React 中呈现 HTML 评论?

node.js - react-router 无法解析模块历史,缺少 lib 文件夹

css - 如何在 react 中隐藏具有内联条件样式的链接?

reactjs - 在 Redux React 的另一个 Action 中调用一个 Action

javascript - 为什么react-redux将状态与恒等(===)运算符进行比较?对象不能以这种方式进行比较

javascript - 过滤函数 ng-repeat 返回 true 但显示 0 个结果

javascript - 我怎样才能在模态(bootstrap)中获得元素宽度/高度

javascript - Vue Jest 测试元素的内联样式