我的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/